从jquery调用MVC操作并处理重定向或返回的部分视图

时间:2012-09-07 01:03:25

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

我想调用我的操作并让该操作返回直接呈现在视图上的结果局部视图,或者让操作重定向到服务器上的另一个页面。

然而,当我通过jQuery执行此操作时,它似乎将重定向的页面加载到我的目标div元素中,而不是重新定向并且有效地重新加载页面/站点。

jQuery调用:

$.ajax({
     type: "GET",
     url: "Myurl",
     dataType: "html",
     success: function (data) {
         // replace the context of the section with the returned partial view
         $('#upload_section').html(data);
     }
 });

MVC动作示例

public ActionResult MyAction() 
{
   bool doRedirect = // some code to determine this condition
   if (doRedirect)
   {
      return RedirectToAction("MyAction", "Home");
   }
   else
   {
      // return the partial view to be shown
      return PartialView("_UploadSessionRow");
   }
}

我这样做是错的吗?这样做有更好的练习方法吗?在其他操作和jQuery请求中需要执行此操作,因此我正在寻找一种常见的方法来解决此问题。

更新: 感谢安德鲁斯的回答,我根据他的建议进行了一些修改,改变了我的ajax。最后的ajax是:

function loadOrRedirect(options) {

    var jData = null;

    try {    
        if (options.data) {
            jData = $.parseJSON(options.data);

            if (jData.RedirectUrl) {
                window.location = jData.RedirectUrl;
            }
        }
    } catch (e) {
        // not json
    }

    if (!jData && options.callback) {
        options.callback(options.data);
    }
};

$.ajax({
     type: "GET",
     url: "Myurl",
     dataType: "html",
     success: function (data) {
         loadOrRedirect(
                       {
                          data: data,
                          callback: function (html) {
                                    replaceRow.replaceWith(html);
                                    alternateRowHighlighting();
                       }
         });
}

});

2 个答案:

答案 0 :(得分:18)

您无法从AJAX请求重定向。您将不得不从JavaScript进行重定向。我会推荐这样的东西:

public ActionResult MyAction() 
{
   bool doRedirect = // some code to determine this condition
   if (doRedirect)
   {
      return Json(new 
      {
          RedirectUrl = Url.Action("MyAction", "Home")
      });
   }
   else
   {
      // return the partial view to be shown
      return PartialView("_UploadSessionRow");
   }
}

然后在JavaScript方面:

$.ajax({
     type: "GET",
     url: "Myurl",
     dataType: "html",
     success: function (data) {
         if (data.RedirectUrl) {
             window.location = data.RedirectUrl;
         } else {
             // replace the context of the section with the returned partial view
             $('#upload_section').html(data);
         }
     }
 });

答案 1 :(得分:0)

您可以使用success回调的第二个或第三个参数来确定要执行的操作。无论如何,由于您使用的是ajax,因此无法进行正常的重定向。您可能必须通过javascript进行辅助重定向或将整个页面替换为RedirectToAction

返回的内容
相关问题