Html.EditorForModel and Hiding element from Edit

2019-04-19 06:32发布

问题:

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....

回答1:

Use [ScaffoldColumn(false)] to hide fields



回答2:

You could use the [HiddenInput] attribute:

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