首页 > 解决方案 > 使用ajax调用后从控制器返回的数据

问题描述

我有以下 Ajax 调用:

$.ajax({
  url: '@Url.Action("DeleteUser", "Tribes")',
  dataType: "json",
  type: "Post",
  data: {
    "tribeId": tribeId,
    "buId": buId,
    "userId": userId
  },
  success: function(data) {
    if (data.status === "success") {
      $.smallBox({
        title: "<strong>User Deleted</strong>",
        content: "<i class='fa fa-clock-o'></i> <i>Tribe user was successfully deleted! <strong></strong></i>",
        color: "#659265",
        iconSmall: "fa fa-check fa-2x fadeInRight animated",
        timeout: 4000
      },
      function(data) {
        window.location.href = '@Url.Action("ViewTribeUsers", "Tribes", new 
        { 
          tribeId = data.tribeId, 
          buId = data.buId 
        })';
      });
    }
  }
});

我的控制器如下所示:

public ActionResult DeleteUser(int tribeId, int buId, string userId)
{
  clsTribes.DeleteTribeUsers(tribeId, userId);
  return Json(new 
  { 
    status = "success", 
    tribeId = tribeId, 
    buId = buId 
  }, JsonRequestBehavior.AllowGet);
}

如何data.[variables]在 AJAX 调用之后使用?在这种情况下,我得到的错误是在这一行的 data.[variable] 上:

 window.location.href = '@Url.Action("ViewTribeUsers", "Tribes", new 
 { 
   tribeId = data.tribeId, 
   buId = data.buId 
 })';

错误:当前上下文中不存在名称“数据”

我相信它一定很简单,任何帮助将不胜感激!

谢谢!

标签: jqueryajaxasp.net-mvc

解决方案


问题是因为data它是一个客户端 JS 变量,您不能在服务器端 C# 代码中使用它。

一种可能的解决方法是使用Url.Action构建基本 URL,然后将属性附加data到它,如下所示:

function (data) {
  window.location.href = '@Url.Action("ViewTribeUsers", "Tribes")?tribeId=' + data.tribeId + '&buId=' + data.buId;
});

这样做的缺点是您不会获得路由此 URL 的好处。它也变得更难维护,因为如果您更改路由模式,您需要记住更新此 JS 逻辑。


推荐阅读