MVC 3 View does not update after sending model

I have a strange problem with my view in an MVC 3 project. I have a standard view for editing data (created using a template). When I submit the form, I change the property Name, but after I returned to the browser from the controller, I still see the value lorem. 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; }
}
+5
source share
4 answers

You need to remove the value from ModelStateif you want to change it in the message / get:

[HttpPost]
public ViewResult EditUserData(UserData model)
{
    ModelState.Remove("Name");
    model.Name = "ipsum";
    return View("~/Views/UserDetails.cshtml", model);    
}

This is the built-in behavior of MVC: everyone Html.Helpersprefers the values ​​in the collection ModelStateover the actual values ​​of the model.

: ASP.NET MVC Postbacks HtmlHelper Controls .

+7

. MVC , , post-. . .

+3

...

[HttpPost]
public ViewResult EditUserData(UserData model)
{
   UserData newmodel = new UserData();
   ModelState.Clear();
   model = newmodel;
   return View("~/Views/UserDetails.cshtml", model);    
}
0

ModelState ( , ) . , :

var newVal = new ValueProviderResult("updated value", "updated value", CultureInfo.InvariantCulture);
ModelState.SetModelValue("MyFieldName", newVal);

.NET/MVC ModelStateDictionary.SetModelValue() , , .

0
source

All Articles