防止 MVC 中的多次提交
在这个问题中,禁用提交按钮以防止多次回发是阻止(非恶意)用户回发的可行解决方案多次。
如果您的视图具有多个提交按钮,则此选项效果不佳。以下面的例子为例。
//View:
@using (Html.BeginForm("Catalog", "Images", FormMethod.Post, new { onsubmit = "Utility.disable_buttons(this.id);", id = "catalog_form" }))
{
<p>
<input type="submit" name="btnSubmit" value="Clear" /> |
<input type="submit" name="btnSubmit" value="Catalog" /> |
<input type="submit" name="btnSubmit" value="Update" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
//Controller:
[HttpPost]
public ActionResult Catalog(string btnSubmit)
{
switch (btnSubmit)
{
case "Catalog":
//More differenter code
break;
case "Clear":
//Different code
break;
case "Nothing":
//Code
break;
}
return View();
}
在视图中,有三种不同的提交操作。如果按钮被禁用,那么它们的值将不会被传递,控制器将不知道哪个按钮触发了提交。 (控制器总是获取 null。)不幸的是,submitdisabledcontrols 属性似乎并没有解决 MVC 中的这个问题。有人知道如何将禁用控件的值传递给服务器吗?
In this question disabling the submit button to prevent multiple postbacks was a viable solution to stop (non-malicious) users from posting back multiple times.
This option doesn't work well if you have a view with multiple submit buttons. Take the following example.
//View:
@using (Html.BeginForm("Catalog", "Images", FormMethod.Post, new { onsubmit = "Utility.disable_buttons(this.id);", id = "catalog_form" }))
{
<p>
<input type="submit" name="btnSubmit" value="Clear" /> |
<input type="submit" name="btnSubmit" value="Catalog" /> |
<input type="submit" name="btnSubmit" value="Update" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
//Controller:
[HttpPost]
public ActionResult Catalog(string btnSubmit)
{
switch (btnSubmit)
{
case "Catalog":
//More differenter code
break;
case "Clear":
//Different code
break;
case "Nothing":
//Code
break;
}
return View();
}
In the view, there are three different submit actions. If the buttons are disabled, then their values won't be passed and the controller will not know which button triggered the submit. (The controller always gets null.) Unfortunately, the submitdisabledcontrols attribute does not seem to solve this problem in MVC. Does anybody know how to pass disabled control's values to the server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一些背景信息:
如果您想禁用所有按钮,使它们不再可单击,但仍然想知道用户单击了什么,我能想到的唯一解决方案是隐藏字段用这个代码:
如果您只是想确保用户在单击一个按钮后无法单击其他按钮,您可以这样做:
不幸的是,没有解决方案(我知道)可以将处理程序绑定到表单的提交并确定单击了哪个输入。这不是与您的问题相关的问题,但使上面的代码稍微复杂一些。
Some background info:
If you want to disable all buttons so they are no longer clickable but still want to know what the user clicked the only solution I can think of is a hidden field along with this code:
If you just want to make sure the user cannot click the other buttons after clicking one you can do this:
Unfortunately there is no solution (I know of) to bind a handler to the form´s submit and determine which input was clicked. This is not a problem related to your question but makes the above code slightly more complicated.
你可以试试这个
you can try this