ASP.NET MVC部分查看ajax帖子?

Ali*_*hşi 14 javascript asp.net-mvc jquery asp.net-mvc-3 asp.net-mvc-4

Index.html(查看)

<div class="categories_content_container">
    @Html.Action("_AddCategory", "Categories")
</div>
Run Code Online (Sandbox Code Playgroud)

_AddCategory.cshtml(PartialView)

<script>
    $(document).ready(function () {
        $('input[type=submit]').click(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: '@Url.Action("_AddCategory", "Categories")',
                dataType: "json",
                data: $('form').serialize(),
                success: function (result) {
                    $(".categories_content_container").html(result);
                },
                error: function () {

                }
            });
        });
    });
</script>

@using (Html.BeginForm())
{
    // form elements
}
Run Code Online (Sandbox Code Playgroud)

调节器

[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
    if(//success)
    {
        // DbOperations...
        return RedirectToAction("Categories");
    }
    else
    {
        // model state is not valid...
        return PartialView(viewModel);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:如果操作成功,我希望重定向到另一个页面(类别).但没有动作,没有错误信息.如果操作不成功,它就像我预期的那样工作.

我怎样才能做到这一点?如何使用AJAX帖子路由另一个页面?

Dar*_*rov 30

不要从使用AJAX调用的控制器操作重定向.这毫无用处.您可以将要重定向的URL作为JsonResult返回:

[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
    if(//success)
    {
        // DbOperations...
        return Json(new { redirectTo = Url.Action("Categories") });
    }
    else
    {
        // model state is not valid...
        return PartialView(viewModel);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在客户端测试此URL的存在并采取相应的行动:

$.ajax({
    type: "POST",
    url: '@Url.Action("_AddCategory", "Categories")',
    data: $('form').serialize(),
    success: function (result) {
        if (result.redirectTo) { 
            // The operation was a success on the server as it returned
            // a JSON objet with an url property pointing to the location
            // you would like to redirect to => now use the window.location.href
            // property to redirect the client to this location
            window.location.href = result.redirectTo;
        } else {
            // The server returned a partial view => let's refresh
            // the corresponding section of our DOM with it
            $(".categories_content_container").html(result);
        }
    },
    error: function () {

    }
});
Run Code Online (Sandbox Code Playgroud)

还要注意我已经dataType: 'json'从你的$.ajax()通话中删除了参数.这是非常重要的,因为我们并不总是返回JSON(在您的情况下,您永远不会返回JSON,所以这个参数是绝对错误的).在我的示例中,我们仅在成功的情况下返回JSON,在text/html失败的情况下返回(PartialView).所以你应该让jQuery简单地使用Content-Type服务器返回的HTTP响应头来自动推断出类型,并相应地解析传递给你的成功回调的结果参数.


Dav*_*ich 5

您所做的ajax调用不应该能够重定向整个页面.它仅将数据返回到异步调用.如果你想进行重定向,我

javascript的重定向方式是window.location

所以你的ajax调用应该是这样的:

<script>
    $(document).ready(function () {
        $('input[type=submit]').click(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: '@Url.Action("_AddCategory", "Categories")',
                dataType: "json",
                data: $('form').serialize(),
                success: function (result) {
                    window.location='@Url.Action("Categories")';
                },
                error: function () {

                }
            });
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

在你的action方法中,不是返回部分或重定向,而是返回Json(true);

public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
    if(//success)
    {
        return Json(true);
    }
    else
    {
        return Json(false);
    }
}
Run Code Online (Sandbox Code Playgroud)