3

我在表单上有 4 个按钮,“提交 1”调用控制器 A,“提交 2”调用控制器 B。

我在同一个表单上也有“按钮 1”和“按钮 2”,我不希望验证发生/触发这些。

如何使“提交 1”和“提交 2”验证表单而不是“按钮 1”和“按钮 2”?

同时'Button 1'和'Button 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”字段中有值并重定向到另一个控制器(比如说。我单击“按钮 2”我不验证任何内容,只是重定向到另一个控制器。

4

1 回答 1

2

关于提交两个动作,你有两个提交按钮和独立值的正确想法。您可以使用操作中的值来破译您希望如何处理请求。尽管您在一天结束时只会提交一个操作,但您可以在操作中重定向它以处理流程的差异。例如

@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
}

至于禁用验证,您可以disableValidation=true在按钮 1 和 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>
于 2013-07-17T18:35:44.757 回答