Change Model's value in View on Postback

In MVC, if you change any value of the model in the postback action, it won't reflect in the View when it is redisplayed. It is because of the design of the HTML Helpers.

For example, if you have a view like below


<% using (Html.BeginForm()) { %>
    <%= Html.TextBoxFor(m => m.FirstName) %>

    <%= Html.TextBoxFor(m => m.LastName) %>
    <input type="submit" value="OK" />
<% %>


which you are posting to the following action:

[HttpPost]
public ActionResult Sample(SampleModel model)
{
    model.FirstName = "Krish";
    model.LastName = "S";
    return View(model);
}

Here the 'FirstName' Property of the model is changed in the Action. But, when the view is redisplayed the old value will be used.

To avoid this remove the value from the 'ModelState'.So it will rebuild the control agin in the view with new data.

[HttpPost]
public ActionResult Sample(SampleModel model)
{
    ModelState.Remove("FirstName");
    ModelState.Remove("LastName");
    model.FirstName = "Krish";
    model.LastName = "S";
    return View(model);
}

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment