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 ModelState
if you want to modify it in a post/get:
[HttpPost]
public ViewResult EditUserData(UserData model)
{
ModelState.Remove("Name");
model.Name = "ipsum";
return View("~/Views/UserDetails.cshtml", model);
}
This is the built in MVC behavoir: all the Html.Helpers
prefers the values in the ModelState
collection over the actual model values.
There is a good article about this here: ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes.
This is by design. MVC is assuming that you want to show what the user initially submitted when processing a post action. See this related stack overflow post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With