Ajax在视图中不起作用

时间:2017-06-22 11:38:43

标签: jquery ajax asp.net-mvc

我是.net mvc的新手,我正在尝试创建一个请求并提交表单的简单页面。当我使用Ajax进行httppost请求时,该页面不会发布/重定向。

Js文件

<script>
    $(document).ready(function () {

        $("form").submit(function (e) {


            var obj = { 

                Id : @Model.Id,
                Name : '@Model.Name',
                City : '@Model.City',
                Gender : '@Model.Gender',
                Dob : '@Model.Dob'

            };

            $.ajax({

                url: '@Url.Action("Edit","Employee")',
                type: 'POST',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(obj),
                success: function (result) {

                    alert("Success");
                },

                failed: function (result) {

                    alert("Failed");
                }

            });

            return false;

        });

    });

</script>

cshtml查看

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Gender", new List<SelectListItem>
           {
               new SelectListItem { Text = "Male" , Value = "Male"},
               new SelectListItem { Text = "Female" , Value = "Female"}
           }, "Select Gender" , new { @class = "form-control"}) 
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

此处的控制器代码

[HttpPost]
        public ActionResult Edit(Employee emp)
        {            
            EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
            if (ModelState.IsValid)
            {
                employeeBusinessLayer.Modify("Edit", emp);

                return View();
            }

            else return RedirectToAction("Index");

        }

当我点击&#39; Save&#39;时,没有任何反应!我在这里缺少什么?

3 个答案:

答案 0 :(得分:4)

您需要在提交方法中使用 e.preventDefault(); ,如下所示:

&#13;
&#13;
<script>
    $(document).ready(function () {

        $("form").submit(function (e) {

            e.preventDefault(); //prevent default form submit
            var obj = { 

                Id : @Model.Id,
                Name : '@Model.Name',
                City : '@Model.City',
                Gender : '@Model.Gender',
                Dob : '@Model.Dob'

            };

            $.ajax({

                url: '@Url.Action("Edit","Employee")',
                type: 'POST',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(obj),
                success: function (result) {

                    alert("Success");
                },

                failed: function (result) {

                    alert("Failed");
                }

            });

            return false;

        });

    });

</script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在定义obj变量之前,添加以下行:

e.preventDefault();

选择如下输入:

var obj: {
   Id: $('Id').val(),
   Name: $('#Name').val(),
   City: $('#City').val(),
   Dob: $('#Dob').val(),
   Gender: $("#Gender option:selected").val()
}

答案 2 :(得分:0)

根据您发布的控制器代码,更改视图的这一部分:

    $("form").submit(function (e) {
        e.preventDefault();

        $.ajax({

            url: '@Url.Action("Edit","Employee")',
            type: 'POST',
            data: $("form").serialize(),
            success: function (result) {

                alert("Success");
            },

            failed: function (result) {

                alert("Failed");
            }

        });

        return false;

    });

您也应该更改控制器,因为您不应该返回View();,但这又是另一回事......