【问题标题】:Ajax and ASP.NET MVC- Get page URL, not the controller/action URLAjax 和 ASP.NET MVC- 获取页面 URL,而不是控制器/操作 URL
【发布时间】:2019-12-17 10:20:32
【问题描述】:

我有一个从控制器类调用 MVC 操作的 Ajax 方法。

$.ajax({
    type: "GET",
    contentType: "application/json; charset=utf-8",
    url: "/ajax/Updates/Message",

    dataType: "json",
    success: function (response) {
        //data variable has been declared already
        data = response;
    },
    complete: function () {

        if (data !== "") {
            $('#div1').text(window.location.path);
            $('#div2').text(data);
        }
    },

});



[HttpGet]
public async Task < ActionResult > Message()
{
    string d = "test string";
    return Json(d, JsonRequestBehavior.AllowGet);
}

Ajax 方法中的“url”是对操作方法的调用。

如果我想在 Ajax 响应中返回实际页面 URL,而不是控制器/操作 url,该怎么办?

所以这个控制器没有视图或与之相关的任何东西,它更像是一个辅助类。当我在任何其他页面中使用 ajax 时,它不会返回该特定页面的 URL 路径(通过 'window.location.path),例如/Accounts/Summary ,而是返回 Updates/Message (参考控制器和操作)

【问题讨论】:

    标签: ajax asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    网络是无状态的,当您使用 ajax 调用 Updates/Message 时,它​​不知道它是用于页面 Accounts/Summary。您必须将此作为参数(post 或 get)传递,或者您可以尝试 Request.UrlReferrer,它应该包含调用请求的页面的 url。

    【讨论】:

      【解决方案2】:

      我希望这将帮助您尝试此代码:

      ajax 代码

              $.ajax({
                  type: 'GET',
                  url: '@Url.action("Message","Updates")', // url.action(ActionName,ControllerName)
                  success: function (data) {
                  window.location = data; 
                  },
                  error: function (xhr) { // if error occured
                      alert("Error occured.please try again");
                  }
                  dataType: 'json'
              });
      

      行动结果:

        [HttpGet]
              public async Task<ActionResult> Message()
              {
                  string d = "http://www.google.com";
                  return Json(d, JsonRequestBehavior.AllowGet);
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多