asp.netasp.net-mvcmodelstatemodelstatedictionary

Prevent value to be preserved in ModelState


Good day!

ASP.NET MVC makes a good job by storing values of inputs during GET/POST cycle inside ModelState and automagically putting them into inputs in case of validation errors.

But on my form I have CAPTCHA field which shouldn't be preserved during validation errors (CAPTCHA value is regenerated on each request).

I've tried to achieve this by setting

if (TryUpdateModel(model))
{
    // ...
}
else
{
    ModelState.Remove("CaptchaValue"); // ModelState does have CaptchaValue 
    return View(model); // CaptchaValue is empty in model
}

But it doesn't work.

May be there is an attribute which I can apply to my model field to prevent it from preserve in ModelState?

Thanks in advance!


Solution

  • I've found this in nearby thread MVC - How to change the value of a textbox in a post?:

    ModelState.SetModelValue("CaptchaValue", new ValueProviderResult(String.Empty, String.Empty, System.Threading.Thread.CurrentThread.CurrentCulture));
    

    But it seems to be a bit ugly.