简体   繁体   English

验证Asp.net MVC中的两个按钮

[英]Validate two buttons in Asp.net MVC

I have two buttons but I'm only able to validate one. 我有两个按钮,但我只能验证一个。 When the user clicks add and the entire form is not filled out then they get error message but if they click finish instead of giving error messages, it goes to another page but I want to give the error before going to that page. 当用户单击“添加”并且未填写整个表单时,他们会收到错误消息,但是如果单击“完成”而不是给出错误消息,它将转到另一页,但是我想在转到该页面之前给出错误。 This is what I have so far for one: 这是我到目前为止所拥有的:

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

Edit 编辑

@{
    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" />

You're using MVC, so just annotate your ViewModel and submit the form with the built in functionality that the framework supplies for you. 您正在使用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...
}

Your form should also have the name of the Action you're trying to POST to... 你的表格也应该有名称Action你想POST到...

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

You can't validate against the data annotations on your viewmodel in MVC from a button that's not of type submit (well, maybe you can, but probably more work). 您无法通过非submit类型的按钮针对MVC中的视图模型上的数据注释进行验证(嗯,也许可以,但是可能需要更多工作)。

You should then mark both buttons as type submit , then interrogate the name of the button that was clicked once it is sent over. 然后,您应将两个按钮都标记为类型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>

Then in your controller, create a method with this signature. 然后在您的控制器中,使用此签名创建一个方法。 Since you have two submit buttons, the values of the button will be sent along in the request and you can interrogate it. 由于您有两个提交按钮,因此按钮的值将随请求一起发送,您可以对其进行询问。 It will look something like this... 看起来像这样...

[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");
    }
}

More information here - 更多信息在这里-

Handling multiple submit buttons on a form in MVC 在MVC中处理表单上的多个提交按钮

Best Practices for ViewModel validation in MVC MVC中ViewModel验证的最佳做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM