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

时间:2014-02-06 06:32:38

标签: jquery asp.net-mvc asp.net-mvc-4 razor unobtrusive-validation

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

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

当用户点击“保存”按钮时,我想进行Ajax调用。

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

ClientValidationEnabled&在web.config中启用了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>

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

编辑查看代码             @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>

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

行动守则

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

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

模型

公共部门班员工     {         公职人员()         {             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; }

}

我检查渲染的html代码。 data-val =“true”将带有不同的字段。

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:3)

收到ajax响应后添加此代码:

$("form").each(function () { $.data($(this)[0], 'validator', false); });
$.validator.unobtrusive.parse("form");