15

I'm using the following code to render an editor for my model using ASP.NET MVC 3, it works perfect, except for I don't want the user to see or edit the "Id" field in my object.

<% using (Html.BeginForm())
   { %>
    <%: Html.ValidationSummary(true, "Your input has errors, please correct and try again") %>
    <%: Html.EditorForModel(Model)%>

    <input type="submit" value="Update" />
<% } %>

In my model for the ID Field I have the following

[Display(AutoGenerateField = false)]
public int Id{ get; private set; }

Which granted is what I thought would work based on the description of the "AutoGenerateField" parameter. However this isn't working. I don't want to have to build the whole editor just for this one little oddity....

Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173

2 Answers2

20

Use [ScaffoldColumn(false)] to hide fields

Lukáš Novotný
  • 9,012
  • 3
  • 38
  • 46
  • 1
    With the caveat that the field isn't just hidden, but omitted from the rendered view entirely. Thus it will not be returned as form data with POST requests. – ProfK Mar 28 '12 at 11:44
  • 1
    I would look at Darin Dimitrov's solution if you need your ID bound to your post request. – Jeff Reddy Jul 10 '12 at 18:16
20

You could use the [HiddenInput] attribute:

[HiddenInput(DisplayValue = false)]
[Display(AutoGenerateField = false)]
public int Id { get; private set; }
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • `HiddenInput` is probably the better choice over `ScaffoldColumn(false)` since the controller action is probably going to want to correlate whatever it is seeing with the database according to the submitted `Id`. – Carl G May 14 '13 at 21:24