2

Hi I'm using Editorfor() to make a little form that submits view model to the controller. Editorfor() nicely prints input fields of the model but it also prints primary key field. So I want to hide primary key field.

@Html.EditorFor(m=>m.viewmodel)

this is markup that I have.

@Html.HiddenFor(m => m.viewmodel.Id);
@Html.EditorFor(m=>m.viewmodel)

have tried this but does not work. and I wanted to make an approach directly to the model but I'm using EF Designer, so I'm not sure where to begin. Please give me an advice.

tereško
  • 58,060
  • 25
  • 98
  • 150
tamikoon
  • 687
  • 1
  • 7
  • 15

3 Answers3

5

Try this:

[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; 
WannaCSharp
  • 1,898
  • 2
  • 13
  • 19
0

Use a custom editor template. For example:

MyViewModel.cshtml (stored in ~/Views/Shared/EditorTemplates folder, structured like a partial view):

@model MyViewModel
@Html.HiddenFor(m => m.Id)
@Html.EditorFor(m => m.Property1)
@Html.TextboxFor(m => m.Property2)
@Html.TextAreaFor(m => m.Property3)
// Whatever else you want in the template

Then you can just call EditorFor on your model in your view that needs to use it and MVC will know to use your custom template:

@Html.EditorFor(m => m.MyViewModel)

To use a custom display template that isn't based on the name of the type, you can also use the [UIHint] attribute as described here: http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html

mayabelle
  • 9,804
  • 9
  • 36
  • 59
0

Don't create any field for your key attribute. Without a field to check, the validation has nothing to complain about. Later you can supply a value for the primary key in the controller.