Reputation: 905
I written HttpPost method and added validation error for testing.
[HttpPost]
public ActionResult UpdateDate(MyModel model)
{
model.MyEmail = "test";
ModelState.AddModelError("MyEmail", "Email is invalid");
return View("Index", model);
}
I stepped through the code and model.MyEmail is updated with "test". When the return View("Index","model") is called, the email is the original email value and not "test" thus there is no validation error. Why is this?
Thanks.
Upvotes: 1
Views: 1207
Reputation: 218732
When Html.TextBoxFor
helper method tries to generate the input field markup for your model property, It will first look for the ModelStateDictionary and If it gets value from that for your view model property, it will use that value. So In your case, even if you update the view model property values to something else, the updated value will not be used.
If you really want to get the property value you updated inside your action method, You need to explicitly remove that item from the ModelStateDictionary.
You can use ModelState.Remove("SomeKeyForYourFormField")
method to remove an single item where you will replace "SomeKeyForYourFormField"
with your form field name.
[HttpPost]
public ActionResult UpdateDate(MyModel model)
{
model.MyEmail = "test";
ModelState.AddModelError("MyEmail", "Email is invalid"); // No effect ! Read further
ModelState.Remove("MyEmail");
return View("Index", model);
}
You can also use ModelState.Clear()
method if you prefer to clear all the items from the ModelStateDictionary.
Since we are clearing the ModelStateDictionary entry for "MyEmail
", You are not going to see the validation error in your view as the error message you added to the errors collection in ModelStateDictionary is going to be cleared when the next line , ModelState.Remove("MyEmail")
gets executed.
You can swap the order of those lines and see the behavior yourself.
And ofcourse, to see the validation error(s), you need to call the ValidationMessgeFor
helper method for the corresponding property of your view model in your view.
@model MyModel
@using (Html.BeginForm("UpdateDate","Home"))
{
@Html.TextBoxFor(f=>f.MyEmail)
@Html.ValidationMessageFor(g=>g.MyEmail)
<input type="submit" />
}
Upvotes: 2