表格上有4个按钮,“提交1”呼叫控制器A,“提交2”呼叫控制器B.
我在同一表格上也有'按钮1'和'按钮2',我不希望验证发生/触发这些。
如何制作“提交1”和“提交2”以验证表单,而不是“按钮1”和“按钮2”?
同时“按钮1”和“按钮2”应提交给不同的控制器。我如何实现这一目标?
public class SampleForm
{
[Display(Name = "FName: ")]
[Required(ErrorMessage = "Enter FName")]
public string FirstName { get; set; }
[Display(Name = "LName: ")]
[Required(ErrorMessage = "Enter LName")]
public string LastName { get; set; }
[Display(Name = "Bypassid: ")]
[Required(ErrorMessage = "Enter Bypassid")]
public string Bypassid { get; set; }
}
@model SampleForm
@using (Html.BeginForm("SampleForm", "SampleController", FormMethod.Post, new { name = "frmSample", id = "frmSample" }))
{
@Html.LabelFor(model => model.FirstName)
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
@Html.LabelFor(model => model.LastName)
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
@Html.LabelFor(model => model.Bypassid)
@Html.TextBoxFor(model => model.Bypassid)
@Html.ValidationMessageFor(model => model.Bypassid)
<input type="submit" value="Submit 1" name="Command" />
<input type="submit" value="Submit 2" name="Command" />
<button type="button" name="Button 1" value="Button 1">Button 1</button>
<button type="button" name="Button 2" value="Button 2">Button 2</button>
}
我想要“提交1”和“提交2”来使用DataAnnotations验证表单,但是 当我点击“按钮1”时,我想确保“Bypassid”字段中有值并重定向到另一个控制器(Say。 当我点击“按钮2”时,我不会验证任何内容,只是重定向到另一个控制器。
答案 0 :(得分:2)
关于提交两个操作,您有正确的想法,有两个提交按钮和独立的值。您可以使用操作中的值来解释您希望如何处理请求。虽然您只会在一天结束时提交一个操作,但您可以在操作中重定向它以处理进程的差异。 e.g。
@using (Html.BeginForm("BasicAction"))
{
@* controls *@
<input type="submit" value="action1" name="command" />
<input type="submit" value="action2" name="command" />
}
然后,你的控制器:
[HttpPost]
public ActionResult BasicAction(MyModel model, String command)
{
if (ModelState.IsValid)
{
switch (command)
{
case "action1":
return RedirectToAction("Action1", new { model = model });
case "action2":
return RedirectToAction("Action2", new { model = model });
}
}
return View(model);
}
// handle action1
[NonAction]
public ActionResult Action1(MyModel model)
{
// do whatever
}
[NonAction]
// handle action2
public ActionResult Action2(MyModel model)
{
// do whatever
}
就禁用验证而言,您可以在按钮1和按钮1上设置disableValidation=true
。 2,客户端验证将被忽略(我相信这是MVC2)。为此,请在定义这些按钮后添加以下javascript:
<script>
// IDs of the buttons to be disabled
var disabled = ['button1','button2'];
for (var i = 0; i < disabled.length; i++){
document.getElementById(disabled[i]).disableValidation = true;
}
</script>