I had an issue similar to that posted in this related question: mvc 4 textbox not updating on postback
Because I wanted to be a bit more targeted than "nuke it all" I am using ModelState.Remove("propertyname")
instead to just affect specific values in my model.
However even this is too broad for what I want, because this removes any validation information, etc. that might have been accrued for this property.
How can I update the specific posted back value without losing all this other useful state information?
The below code displays the current behaviour, (with unwanted behaviour in bold):
- submitting "test" returns a model with "replacement", but a form with "test"
- submitting "testlong" returns a model with "replacement", but a form with "testlong", and displays a validation message
- submitting "remove" returns a model with "replacement", and form with "replacement"
- submitting "removelong" returns a model with "replacement", and form with "replacement" and no validation message
Model:
public class TestViewModel
{
[StringLength(7, ErrorMessage = "{0} must be less than {1} characters")]
public string A { get; set; }
}
Action:
public ActionResult Test(TestViewModel model)
{
if(model.A == "remove" || model.A == "removelong")
{
ModelState.Remove("A");
}
model.A = "replacement";
return View(model);
}
View:
@model TestNamespace.TestViewModel
@{ Layout = null; }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form>
@Html.ValidationMessageFor(m=>m.A)
@Html.TextBoxFor(m => m.A)
</form>
</body>
</html>
Some examples where this would be useful:
- Telling the user what they got wrong, fixing it for them, and telling them we fixed it.
- An application that logs validation errors for analysis, and always does so as the last step before the view so as to capture validation errors added during the Action.
- Manager/Customer mandated logic which is nonsensical, but still required despite advice to that effect.