0

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!

artvolk
  • 9,448
  • 11
  • 56
  • 85

2 Answers2

1

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

public ActionResult YourActionName([Bind(Exclude = "CaptchaValue")]ModelType model)
Rob West
  • 5,189
  • 1
  • 27
  • 42
  • It seems you get me wrong, I need field to be binded (to get access to it in controller), but I don't need to repopulate it in case of form redisplay (when validation errors occured). – artvolk Jun 16 '11 at 12:49
  • Ah, OK, in which case I guess it will need to be the ugly SetModelValue – Rob West Jun 16 '11 at 13:40
0

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.

Community
  • 1
  • 1
artvolk
  • 9,448
  • 11
  • 56
  • 85
  • 1
    You can add a little syntactic sugar to this by making an extension method ModelState.ClearValue(string PropertyName) which would do SetModelValue for you and should make the code a little cleaner. – Chao Jun 17 '11 at 15:34
  • But how to make it work with any type of a field (both value types and reference types), not just string? – artvolk Jun 18 '11 at 08:24
  • Hmmm not so sure, you might have to dig around in modelbinders to try and work out the type then instantiate it via reflection. – Chao Jun 21 '11 at 15:50