【问题标题】:ASP.NET MVC Partial view ajax post?ASP.NET MVC 部分视图 ajax 帖子?
【发布时间】:2013-01-18 00:05:05
【问题描述】:

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 发布路由另一个页面?

【问题讨论】:

  • 您是否已经尝试添加重定向?你的问题暗示是的,但我在你的代码中看不到这样的功能。
  • OIC,您正试图在您的操作中重定向
  • @DaveA,我的意思是控制器成功,而不是 ajax。我添加return RedirectToAction("Categories"); 进行重定向。如果模型状态无效,则 ajax 发布成功(这是预期的)。我想在控制器动作中重定向,这可能吗?或者如果没有,我怎样才能在 ajax 成功中捕捉到这一点并重定向到另一个页面。总结,如果 DbOperations 成功重定向另一个页面,我想再次使用模型加载 partialView。

标签: javascript jquery asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

不要从使用 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'。谢谢达林!
  • 感谢您提供简单的代码示例。我能够为我的自定义实例非常有效地修改它......但代码清晰是关键。谢谢!
【解决方案2】:

您进行的 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>

在你的action方法中,不是返回一个partial或redirect,而是返回Json(true);

public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
    if(//success)
    {
        return Json(true);
    }
    else
    {
        return Json(false);
    }
}

【讨论】:

  • 那么,我应该返回“true or false”而不是“PartialView 或 RedirectToAction”
  • +1。非常感谢,但@DarinDimitrov 的回答是我想要的。
猜你喜欢
  • 2014-07-14
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2011-06-18
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
相关资源
最近更新 更多