【问题标题】:Validate two buttons in Asp.net MVC验证 Asp.net MVC 中的两个按钮
【发布时间】:2017-09-05 16:51:19
【问题描述】:

我有两个按钮,但我只能验证一个。当用户单击添加并且未填写整个表单时,他们会收到错误消息,但如果他们单击完成而不是给出错误消息,它会转到另一个页面,但我想在转到该页面之前给出错误。这就是我迄今为止所拥有的:

@model student.Models.Student

<h2>Student Record</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Issue</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.studentNumber, htmlAttributes: new { @class = "col-md-2" })
            @Html.EditorFor(model => model.studentNumber, new { htmlAttributes = new { @readonly = "readonly", @id = "reqnum", @class = "form-control" } })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "col-md-2" })
            @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.Label("Processed by:", htmlAttributes: new { @class = "col-md-2" })
            @Html.DropDownListFor(model => model.processedbyDetails.employeeNum, new SelectList(ViewBag.StoresReps, "Value", "Text"), new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.processedbyDetails.employeeNum, "", new { @class = "text-danger" })

        </div>

        @* -- MANY OTHER INPUTS -- *@


        <div class="form-group">
            <div class="col-md-offset-4 col-md-12">
                <input type="submit" value="Add" name="Add" class="btn btn-default" width="89" />
                <input type="button" value="Finish" name="Issue" margin="50px" onclick="location.href='@Url.Action("ViewIssue", "Issue")' " class="btn btn-default" />
                <input type="button" value="Cancel" name="Cancel" margin="50px" onclick="location.href='@Url.Action("Cancel", "Issue")' " class="btn btn-default" />
            </div>
        </div>
    </div>
}

编辑

@{
    ViewBag.Title = "Student Item";
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

<script type="text/javascript">

<script type="text/javascript">
 function onFinishClick() {
        if ($('form').valid()) {
            location.href = '@Url.Action("ViewIssue", "Issue")';
            }
            return false;
            }
</script>


<input type="button" value="Finish" name="Issue" margin="50px" onclick="onFinishClick()" class="btn btn-default" />

【问题讨论】:

标签: c# jquery asp.net asp.net-mvc


【解决方案1】:

您正在使用 MVC,因此只需注释您的 ViewModel 并使用框架为您提供的内置功能提交表单。

public class Student
{
    [StringLength(100)]
    [DisplayName("Student Name")]
    [Required(ErrorMessage = "Please enter a Student Name")]
    public string Name { get; set; }

    [StringLength(100)]
    [DisplayName("Student Number")]
    [Required(ErrorMessage = "Please enter a Student Number")]
    public string StudentNumber { get; set; }

    // etc...
}

您的表单还应该包含您尝试将POST 发送到...的Action 的名称...

@using (Html.BeginForm("AddOrFinish", "HomeController", FormMethod.Post, new { role = "form" }))

您无法通过不属于 submit 类型的按钮验证 MVC 中视图模型上的数据注释(嗯,也许可以,但可能需要更多工作)。

然后您应该将两个按钮标记为类型submit,然后在发送后询问被单击的按钮的名称。

    <div class="form-group">
        <div class="col-md-offset-4 col-md-12">
            <input type="submit" value="Add" name="add" class="btn btn-default" width="89" />
            <input type="submit" value="Finish" name="issue" margin="50px" class="btn btn-default" />
            <input type="button" value="Cancel" name="Cancel" margin="50px" onclick="location.href='@Url.Action("Cancel", "Issue")' " class="btn btn-default" />
        </div>
    </div>

然后在您的控制器中,使用此签名创建一个方法。由于您有两个提交按钮,因此按钮的值将在请求中发送,您可以查询它。它看起来像这样......

[HttpPost]
public ActionResult AddOrFinish(Student model, string add, string issue)
{
    if (!ModelState.IsValid)
    {
        return RedirectToAction("PageImOnNow", model);
    }

    if (!string.IsNullOrEmpty(add))
    {
        // do your add logic
        // redirect to some page when user clicks "Add"
        return RedirectToAction("WhateverPageYouWant");
    }
    else
    {
        // do your finish logic
        // redirect to ViewIssue page when user clicks "Finish"
        return RedirectToAction("ViewIssue");
    }
}

更多信息在这里 -

Handling multiple submit buttons on a form in MVC

Best Practices for ViewModel validation in MVC

【讨论】:

  • 它正在重定向到另一个不存在的页面,我在哪里将其更改为正确的 url。当我添加它时,它假设保留在页面上,但是当它完成时它被重定向
  • @Jane 好吧,看看你的控制器名称和其中的视图。我假设HomeControllerViewIssue,但这是一个示例,您需要将其更新为实际属于您的视图和控制器。
  • 在添加和完成重定向时如何让它成为一页。
  • @Jane 这就是我的例子。当它完成时它重定向,如果它是添加,你可以让它去其他地方 - 见编辑。
  • 我有,但是它仍然重定向到另一个页面,不确定是不是因为这个 AddOrFinish", "HomeController", FormMethod.Post, new { role = "form"
猜你喜欢
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2011-04-14
  • 2014-10-12
  • 2013-08-25
  • 2011-08-05
相关资源
最近更新 更多