防止值保留在 ModelState 中

发布于 2024-11-16 05:28:00 字数 463 浏览 4 评论 0原文

再会!

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

删除会话 2024-11-23 05:28:00

您可以使用操作参数上的绑定属性来控制模型绑定行为:

public ActionResult YourActionName([Bind(Exclude = "CaptchaValue")]ModelType model)

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

public ActionResult YourActionName([Bind(Exclude = "CaptchaValue")]ModelType model)
吃不饱 2024-11-23 05:28:00

我在附近的线程 中找到了这个MVC - 如何更改帖子中文本框的值?

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

但它似乎有点难看。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文