tags:

views:

237

answers:

2

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

+2  A: 

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.

Gidon
thanks, worked for me as well, thanks! but it should be more simple than this...
Paulo
A: 

I have not tried this yet as I'm not available to but this should work if I'm not mistaken.

ModelState.AddModelError("Name", "Some error message.");
ModelState["Name"].Value = "Value";

You could wrap this in a extension method for ModelState...

public static class ModelStateExtensions
{
    public static void AddModelError(this ModelStateDictionary modelState, string key, string message, string value)
    {
        modelState.AddModelError(key, message);
        modelState[key].Value = value;
    }
}
Chad Moran
Doesn't work because the type of Value is ValueProviderResult.
Paulo