Html.DisplayFor not posting values to controller i

2019-01-14 11:07发布

问题:

I am using ASP.NET MVC 3 with Razor, below is a sample from my view code.

The user should be able to edit all their details, except the "EmailAddress" field. For that field only I have used Html.DisplayFor(m => m.EmailAddress).

But when this form gets posted, all the model properties are filled except the EmailAddress.

How do I get the email back in the model when posting? Should I have used some helper other than DisplayFor?

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true, "Account update was unsuccessful. Please correct any errors and try again.")
    <div>
        <fieldset>
            <legend>Update Account Information</legend>
            <div class="editor-label">
                @Html.LabelFor(m => m.EmailAddress)
            </div>
            <div class="editor-field">
                @Html.DisplayFor(m => m.EmailAddress)
                @*@Html.ValidationMessageFor(m => m.EmailAddress)*@
            </div>           
            <div class="editor-label">
                @Html.LabelFor(m => m.FirstName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.FirstName)
                @Html.ValidationMessageFor(m => m.FirstName)
            </div>
            <div class="editor-label">
                @Html.LabelFor(m => m.LastName)
            </div>
            <div class="editor-field">
            @Html.TextBoxFor(m => m.LastName)
                @Html.ValidationMessageFor(m => m.LastName)
            </div>
            <p>
                <input type="submit" value="Update" />                
            </p>
        </fieldset>
    </div>
}

Please advise me on this.

回答1:

you'll need to add a

@Html.HiddenFor(m => m.EmailAddress)

DisplayFor won't send anything in POST, it won't create an input...

By the way, an

@Html.HiddenFor(m => m.Id) // or anything which is the model key

would be usefull