防止值保留在 ModelState 中
再会!
ASP.NET MVC 做得很好,它在 GET/POST 循环期间将输入值存储在 ModelState 内,并在出现验证错误时自动将它们放入输入中。
但在我的表单上,我有验证码字段,在验证错误期间不应保留该字段(验证码值在每个请求时重新生成)。
我试图通过设置来实现这一点
if (TryUpdateModel(model))
{
// ...
}
else
{
ModelState.Remove("CaptchaValue"); // ModelState does have CaptchaValue
return View(model); // CaptchaValue is empty in model
}
,但它不起作用。
可能有一个属性可以应用于我的模型字段以防止它保留在 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用操作参数上的绑定属性来控制模型绑定行为:
You can use the bind attribute on the action parameter to control model binding behaviour:
我在附近的线程 中找到了这个MVC - 如何更改帖子中文本框的值?:
但它似乎有点难看。
I've found this in nearby thread MVC - How to change the value of a textbox in a post?:
But it seems to be a bit ugly.