我有以下观点,如果提交提交按钮被垃圾邮件,我怎么能不允许用户只提交一次表单
<h2>Add new Storage</h2>
<br /><br />
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DateFrom)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateFrom)
@Html.ValidationMessageFor(model => model.DateFrom)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DateTo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateTo)
@Html.ValidationMessageFor(model => model.DateTo)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Size)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Size)
@Html.ValidationMessageFor(model => model.Size)
</div>
<br />
<p>
<input type="submit" value="Create" />
</p>
}
<br />
<div>
@Html.ActionLink("View all storage", "ViewStorage")
</div>
控制器:
[HttpGet]
public ActionResult Add()
{
ViewBag.Storage = new BusinessLayer.Storage().getAllStorage();
return View();
}
[HttpPost]
public ActionResult Add(Models.ActivityModel activity)
{
if (activity.Storage != null)
{
if (new BusinessLayer.Activities().addActivity(activity.Storage, activity.Name, activity.Date, activity.Keywords))
{
return RedirectToAction("Home", "Home");
}
}
else
{
ModelState.AddModelError("", "An error occurred, please try again!");
}
ViewBag.Storage = new BusinessLayer.Storage().getAllStorage();
return View(activity);
}
答案 0 :(得分:0)
没有正确的方法可以检测您的表单是否有意提交多次,您应该组织您的业务模型,以便它不会验证/接受重复或任何无效的输入。
类似的东西:
public ActionResult Add(Models.ActivityModel activity)
{
if (activity.Storage != null && validator.isValid(activity.Storage))
{
if (new BusinessLayer.Activities().addActivity(activity.Storage, activity.Name, activity.Date, activity.Keywords))
{
return RedirectToAction("Home", "Home");
}
}
else
{
ModelState.AddModelError("", "An error occurred, please try again!");
}
ViewBag.Storage = new BusinessLayer.Storage().getAllStorage();
return View(activity);
}
其中validator.isValid(Models.ActivityModel.Storage storage)
检查重复项,有效输入等。
与您的相关的另一个问题是表单重新提交,当每次刷新页面时多次提交表单时,您可以通过实现Post-Redirect-Get
pattern来修复它