ASP.NET MVC的局部视图Ajax提交?

15

Index.html(视图)

<div class="categories_content_container">
    @Html.Action("_AddCategory", "Categories")
</div>

_AddCategory.cshtml (部分视图)

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

控制器

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

问题:如果操作成功,我希望重定向到另一个页面(类别),但没有任何动作,也没有错误消息。如果操作不成功,则按照我的预期工作。

我该怎么做?如何在使用 AJAX post 的情况下路由到另一页?


你已经尝试添加重定向了吗?你的问题似乎是肯定的,但我在你的代码中没有看到这样的功能。 - Dave Alperovich
抱歉,您正在尝试在操作中进行重定向。 - Dave Alperovich
@DaveA,我的意思是在控制器成功时,而不是ajax。我添加了return RedirectToAction("Categories");来进行重定向。如果模型状态无效,则ajax post成功(这是预期的)。我想在控制器操作中重定向,这可能吗?或者如果不行,我该如何在ajax成功时捕获它并重定向到另一个页面。总之,如果DbOperations成功,则重定向到另一页,否则重新加载带有模型的partialView。 - AliRıza Adıyahşi
2个回答

32

不要从使用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);
    }
}

然后在客户端测试该 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 () {

    }
});

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


我遇到了同样的问题,因为dataType是'json'。谢谢Darin! - Chronozoa
感谢您提供的简单代码示例。我能够相当有效地修改它以适应我的自定义实例...但代码的清晰度是关键。谢谢! - Eric Burdo

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>

在你的操作方法中,不要返回部分视图或重定向,而应该返回Json(true)。
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
    if(//success)
    {
        return Json(true);
    }
    else
    {
        return Json(false);
    }
}

那么,我应该返回“true或false”而不是“PartialView或RedirectToAction”吗? - AliRıza Adıyahşi
+1。非常感谢,但是@DarinDimitrov的回答正是我想要的。 - AliRıza Adıyahşi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接