Partial View - client validation is not working with jquery ajax post
Asked Answered
C

2

6

In Index page I show list of employees, when user click on Edit link the I show a Edit View.

This Edit View renders a partial view (_EditPartial) to show different fields which are edititable.

When user click on save button I want to make a Ajax post call.

I want to validate the inputs before posting the data to server. I tried using unobtrusive validations but validation is not triggering at all for me. Following is the code snippet.

ClientValidationEnabled & UnobtrusiveJavaScriptEnabled are enabled in the web.config.

Code snippet

Partial View code

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

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

Edit View Code @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>

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

Action Code

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

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

Model

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

}

I check the rendered html code. data-val="true" is coming with differet fields.

Can anybody please help how to use client validation with with ajax post call.

Cymophane answered 6/2, 2014 at 6:32 Comment(0)
E
4

You have to check if your form is valid. In your code, the $(this) references the btnSave button, not your form.

Try changing your code to this:

<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>
Emmet answered 10/2, 2014 at 19:31 Comment(0)
T
3

Add this code after receiving the ajax response:

$("form").each(function () { $.data($(this)[0], 'validator', false); });
$.validator.unobtrusive.parse("form");
Tonry answered 28/7, 2014 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.