【问题标题】:Call MVC action from jquery and handle redirect or a returned partial view从 jquery 调用 MVC 操作并处理重定向或返回的部分视图
【发布时间】:2012-09-07 01:03:25
【问题描述】:

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

但是,当我通过 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();
                       }
         });
}

});

【问题讨论】:

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


【解决方案1】:

您不能从 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);
         }
     }
 });

【讨论】:

  • 谢谢安德鲁。我试试看。
  • 是的,我在我的回答中更新了一些次要的模组来治疗
【解决方案2】:

您可以使用success 回调的第二个或第三个参数来确定要做什么。无论如何,由于您使用的是 ajax,您将无法进行正常的重定向。您可能需要通过 javascript 进行二次重定向或将整个页面替换为从 RedirectToAction 返回的内容

【讨论】:

  • 干杯约翰。我设法通过返回一个 Json 对象并在 javascript 中进行重定向来做到这一点。
猜你喜欢
  • 2013-09-11
  • 2016-12-29
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
相关资源
最近更新 更多