MVC3 JSON返回编辑页面

时间:2012-08-03 15:04:43

标签: asp.net json asp.net-mvc-3

所以我有一些javascript代码将数据发送到我的控制器:

使用Javascript:

<script type="text/javascript">
        $(document).ready(function () {
            $("#newGrade").click(function () {
                var newGradeName = $("#newGradeName").val();
                var newGradeValue = $("#newGradeValue").val();
                var vSchoolID = $("#SchoolID").val();

                if (newGradeName != null && newGradeValue != null) {
                    $.ajax({
                        url: '@Url.Action("NewGrade", "School")',
                        data: { gradeName: newGradeName, gradeValue: newGradeValue, schoolID: vSchoolID },
                        type: 'POST',
                        traditional: true,
                        success: function (data) {
                            if (data.status)
                                window.location = data.route;
                        },
                        error: function () {
                            return false;
                        }
                    });
                }
            });
        });
    </script>

控制器:

  public ActionResult NewGrade(String gradeName, Int32 gradeValue, Guid schoolID)
    {
        School school = schoolRepository.GetByID(schoolID);
        school.Grades.Add(
            new Grade
            {
                GradeID = Guid.NewGuid(),
                Name = gradeName,
                NumericalValue = gradeValue
            });
        schoolRepository.Update(school);
        schoolRepository.Save();
        if (Request.IsAjaxRequest())
        {
            var json = new { status = true, route = Url.RouteUrl(new { action = "Edit", id = schoolID }) };
            return Json(json, JsonRequestBehavior.AllowGet);
        }
        return View();
    }

我现在的问题是我想要返回我的编辑页面(可能刷新页面,但不刷新数据,或只刷新整个页面),但我的编辑页面带有ID(schoolID)。按下按钮进入编辑页面时显示此处:

<a href="@Url.Action("Edit", "School", new { id = Model.School.SchoolID })"><i class="icon-pencil"></i>&nbsp;Edit</a>

1 个答案:

答案 0 :(得分:2)

尝试window.location.href,看看会发生什么。

success: function(data) {
                        if (data.status)
                            window.location.href = data.route;
                    },

假设您从

等操作方法获得JSON响应,这应该可以正常工作
{"status":"true","route":"/School/Edit/1"}

其中1是新记录的ID。