maxopie maxopie - 3 months ago 9
ASP.NET (C#) Question

Saving Errors When Clearing a Form (MVC)

I'm new to using MVC 5 and .NET framework 4.5 and I have encountered an issue. I have a form, and I want to reset the fields of the form when it errors out, but keep the errors and display to the user. Currently I can clear the fields on error, but this also gets rid of the errors. I have tried

originalModel.field= "";


but this doesn't clear the field. I have also tried just using

ModelState.Clear();


But this doesn't do anything either.

This is what I'm currently working with (which clears everything):

if (!ModelState.IsValid)
{
TestModel blank= new TestModel();
ModelState.Clear();
return View("View.cshtml", blank);
}

Answer

If you absolutely need this behavior, you can go and set the value of this property of your view model to empty string in the Modelstate dictionary.

[HttpPost]
public virtual ActionResult Index(CreatePostVm model)
{
  if (ModelState.IsValid == false)
  {
     ModelState["PostTitle"].Value =
          new ValueProviderResult(string.Empty, string.Empty,CultureInfo.InvariantCulture);

     return View(model);
  }
  // to do : Return something
}

The above code will set the PostTitle property of your CreatePostVm view model to an empty text. So in your view, the input field will be an empty text while still displaying the validation error message for PostTitle field.

Comments