部分视图 - 客户端验证不适用于jquery ajax帖子

Atu*_*eka 6 asp.net-mvc jquery razor unobtrusive-validation asp.net-mvc-4

在索引页面中,我显示了员工列表,当用户单击编辑链接时,我显示了编辑视图.

此编辑视图呈现部分视图(_EditPartial)以显示可编辑的不同字段.

当用户单击"保存"按钮时,我想进行Ajax调用.

我想在将数据发布到服务器之前验证输入.我尝试使用不引人注目的验证,但验证根本不会触发我.以下是代码段.

在web.config中启用ClientValidationEnabled和UnobtrusiveJavaScriptEnabled.

代码段

部分视图代码

        @model WebApplication1.Models.employee

        <div id="mypartial" class="form-horizontal">
            <h4>employee</h4>
            <hr />
            @Html.ValidationSummary(true)
            @Html.HiddenFor(model => model.id)

            <div class="form-group">
                @Html.LabelFor(model => model.name, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.name)
                    @Html.ValidationMessageFor(model => model.name)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.age, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.age)
                    @Html.ValidationMessageFor(model => model.age)
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.address, new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.address)
                    @Html.ValidationMessageFor(model => model.address)
                </div>
            </div>              
        </div>
Run Code Online (Sandbox Code Playgroud)

===================

编辑视图代码@model WebApplication1.Models.employee

        @{
            Layout = null;
        }

        <!DOCTYPE html>

        <html>
        <head>
            <meta name="viewport" content="width=device-width" />
            <title>Edit</title>
            <script src="~/Scripts/jquery-2.1.0.js"></script>

            <script type="text/javascript">
                $(document).ready(function () {

                    $("#btnSave").click(function () {
                        $("#btnSave").click(function () {


                            debugger;

                            // For some reason following function always return true even if I put invalide data
                            var v = $(this).valid();

                            $.validator.unobtrusive.parse($("#mypartial"));

                            var data = $('form').serialize();
                            $.ajax({
                                type: "POST",
                                url: "@Url.Action("Edit")",
                                data: data,
                                cache: false
                            })
                            .fail(function (xhr, textStatus, errorThrown) {
                                alert(xhr.responseText);
                            })
                            .success(function () {

                                alert("Success");

                            });
                                });
                    });

                });
            </script>
        </head>
        <body>
            @Scripts.Render("~/bundles/jquery")
            @Scripts.Render("~/bundles/jqueryval")


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

                @Html.Partial("_EditPartial", Model)

                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="button" id="btnSave" value="Save" class="btn btn-default" />
                    </div>
                </div>
            }

        </body>


        </html>
Run Code Online (Sandbox Code Playgroud)

============

行动守则

 [HttpPost]
        public ActionResult Edit([Bind(Include="id,name,age,address")] employee employee)
        {
            // This return falase because input data is invalid
            if (ModelState.IsValid)
            {
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }
Run Code Online (Sandbox Code Playgroud)

===============

模型

public partial class employee {public employee(){this.employeerolemappings = new List(); }

    public int id { get; set; }
    [Required]
    public string name { get; set; }

    [Required]
    public Nullable<int> age { get; set; }
    [Required]
    public string address { get; set; }
Run Code Online (Sandbox Code Playgroud)

}

我检查渲染的HTML代码.data-val ="true"即将出现不同的字段.

任何人都可以帮助如何使用ajax post call使用客户端验证.

小智 4

您必须检查您的表格是否有效。在您的代码中,$(this)引用的是 btnSave 按钮,而不是您的表单。

尝试将您的代码更改为:

<script type="text/javascript">
    $(document).ready(function () {

        $("#btnSave").click(function () {

            var v = $('form').valid();

            var data = $('form').serialize();

            $.ajax({
                type: "POST",
                url: "@Url.Action("Edit")",
                data: data,
                cache: false
            })
            .fail(function (xhr, textStatus, errorThrown) {
                alert(xhr.responseText);
            })
            .success(function () {
                alert("Success");
            });
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)