MVC - How to change the value of a text field in a message?

After the user clicks the submit button of my page, the text field will be checked, and if it is invalid, I will ModelState.AddModelError an error message using the ModelState.AddModelError method. And I need to replace the value of this text box and show the page with error messages to the user.

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

How can i do this?

thanks

+4
source share
3 answers

You can use ModelState.Remove (nameOfProperty), for example:

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

This will work.

+6
source

I also did not know the answer, checked around the ModelState object and found:

ModelState.SetModelValue()

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

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

It worked for me.

+5
source

I have a situation where I want to keep a hidden value between a POST controller. The hidden value changes when other values ​​change. I could not get the hidden element to update without manually updating the value in ModelState.

I did not like this approach, since it was strange not to use a strongly typed reference to the model value.

I found that calling ModelState.Clear just before returning the View result worked for me. It seemed that then she would select the value from the Model, and not the values ​​that were presented in the previous POST.

I think that there will probably be a problem with this approach for situations where you use errors in ModelState, but my script does not use model errors.

+1
source

All Articles