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.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281

1 Answers1

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

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • 1
    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. – Yasser Shaikh Sep 07 '12 at 09:35