Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 The View is not being refreshed after model submit

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; }
}
like image 817
Tony Avatar asked Jun 11 '12 19:06

Tony


2 Answers

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.

like image 129
nemesv Avatar answered Nov 15 '22 10:11

nemesv


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.

like image 28
stephen.vakil Avatar answered Nov 15 '22 09:11

stephen.vakil