4

After a user clicks the submit button of my page, there is a textbox that is validated, and if it's invalid, I show an error message using the ModelState.AddModelError method. And I need to replace the value of this textbox and show the page with the error messages back to the user.

The problem is that I can't change the value of the textbox, I'm trying to do ViewData["textbox"] = "new value"; but it is ignored...

How can I do this?

thanks

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
Paulo
  • 7,123
  • 10
  • 37
  • 34

3 Answers3

6

You can use ModelState.Remove(nameOfProperty) like:

ModelState.Remove("CustomerId");
model.CustomerId = 123;
return View(model);

This will work.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
Jeferson Tenorio
  • 2,030
  • 25
  • 31
5

I didn't know the answer as well, checked around the ModelState object and found:

ModelState.SetModelValue()

My model has a Name property which I check, if it is invalid this happens:

ModelState.AddModelError("Name", "Name is required.");
ModelState.SetModelValue("Name", new ValueProviderResult("Some string",string.Empty,new CultureInfo("en-US")));

This worked for me.

Gideon
  • 18,251
  • 5
  • 45
  • 64
1

I have a situation where I want to persist a hidden value between POST's to the controller. The hidden value is modified as other values are changed. I couldn't get the hidden element to update without updating the value manually in ModelState.

I didn't like this approach as it felt odd to not be using a strongly typed reference to Model value.

I found that calling ModelState.Clear directly before returning the View result worked for me. It seemed to then pick the value up from the Model rather than the values that were submitted in the previous POST.

I think there will likely be a problem with this approach for situations when using Errors within the ModelState, but my scenario does not use Model Errors.

Paul Hicks
  • 11
  • 1
  • 1