is it allowed in ASP.NET MVC to alter the submitted values?
[HttpPost]
public ActionResult Create(Person toCreate)
{
toCreate.Lastname = toCreate.Lastname + "-A-";
return View(toCreate);
}
i tried that code, but ASP.NET MVC keep showing the values submitted by the user
[UPDATE]
this:
[HttpPost]
public ActionResult Create(Person toCreate)
{
return View(new Person { Lastname = "Lennon" });
}
or this:
[HttpPost]
public ActionResult Create(Person toCreate)
{
return View();
}
still shows the values inputted by the user, which led me to thinking, why the generated code need to emit: return View(toCreate) in HttpPost? why not just return View()? at least it doesn’t violate the expectations that the values can be overridden from controller
[UPDATE: 2010-06-29]
Found the answer here: ASP.NET MVC : Changing model's properties on postback and here: Setting ModelState values in custom model binder
Working Code:
[HttpPost]
public ActionResult Create(Person toCreate)
{
ModelState.Remove("Lastname");
toCreate.Lastname = toCreate.Lastname + "-A-";
return View(toCreate);
}
Apparently there is no way to revalidate the ModelState once you change a value of some key. The IsValid remains false because setting a new value to some key does not trigger revalidation.
The solution is to first remove the key that triggered IsValid to be false and recreate it and assign the value to it. When you do that the ModelState automatically revalidates and if everything is fine, IsValid returns true.
Like this: