Question

This is an MVC - razor question. [The environment is MVC 4.0.] I have a view model with one editable property and one display-only property. In my view, I am using @html.TextBoxFor() method for the editable property. In order to display the display-only property, I am directly putting @Model.Property. I have a server-side validation on the Editable property and if the posted value for the Editable property is NOT valid, I am returning the same view with the validation error in the validation summary section of the view. Now, here is the problem - After submitting the View form with invalid value for the editable property, I see the error for the editable property, but the display-only property is blank. Does MVC posting BLANK/Nothing for my Display-only property ? How do I get around this issue ?

Was it helpful?

Solution

If you would like to exclude view model attributes you can use a combination of the Bind Attribute and an interface with just the properties you want to include when model binding on the server.

See here: http://www.dotnetcurry.com/ShowArticle.aspx?ID=439

OTHER TIPS

If you are not keeping it the property on a form field(Input etc..), It won't be availbale when you post it.

Use @Html.HiddenFor method keep the property (along with displaying it) in your form so that it will be available when you post it.

@model YourCustomerViewModel
@using(Html.BeginForm())
{
  <span>@Model.EmailAddress</span>
  @Html.TextBoxFor(s=>s.FirstName)

  @Html.HiddenFor(s=>s.EmailAddress)
  <input type="submit" value="Save" />
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top