Ajax 和 ASP.NET MVC - 获取页面 URL,而不是控制器/操作 URL



我有一个从控制器类调用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,而是返回更新/消息(参考控制器和操作(

网络是无状态的,当你用ajax调用更新/消息时,它不知道它是用于页面帐户/摘要的。您必须将其作为参数(post或get(传递,或者您可以尝试Request.UrlReferrer,它应该包含调用请求的页面的URL。

我希望这能帮助你尝试这段代码:

阿贾克斯代码

$.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);
}

最新更新