I have a strange problem with my view in the MVC 3 project. I have a standard view for data editing (created using the template). When I submits the form, I change the Name property, but after I came back to the browser from the controller I still see the lorem value. Why ?
@using (Html.BeginForm())
{
@Html.EditorFor(model => model.Name)
<input type="submit" value="Save" />
}
public ViewResult EditUserData(int id)
{
[...]
UserData model = new UserData();
model.Name = "lorem";
return View("~/Views/UserDetails.cshtml", model);
}
[HttpPost]
public ViewResult EditUserData(UserData model)
{
model.Name = "ipsum";
return View("~/Views/UserDetails.cshtml", model);
}
public class ControlUserData
{
[...]
[Required]
[Display(ResourceType = typeof(Resources), Name = "UserNameFirst")]
public string Name { get; set; }
}
You need to remove the value from the
ModelStateif you want to modify it in a post/get:This is the built in MVC behavoir: all the
Html.Helpersprefers the values in theModelStatecollection over the actual model values.There is a good article about this here: ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes.