Question

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!

Was it helpful?

Solution 2

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.

OTHER TIPS

You can use the bind attribute on the action parameter to control model binding behaviour:

public ActionResult YourActionName([Bind(Exclude = "CaptchaValue")]ModelType model)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top