39

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.

0

1 Answer 1

57

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

Sign up to request clarification or add additional context in comments.

1 Comment

ok so in my case, I would need to have both DisplayFor and HiddenFor right ? DisplayFor will display value to the user, and the HiddenFor will post value back to controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.