这是我的Ajax代码:
$("#generateImage").click(function () {
var url = $(this).data('url');
var currentUrl =window.location.href;
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: url,
data: "{'urlVar':'"+ currentUrl +"','mywidth':'250','myheight':'480'}",
success: function (response) {
if (response != null && response.success) {
alert("Success");
window.location = '@Url.Action("GetData", "MyController", new { urlVar = currentUrl })';
} else {
alert("Failed");
}
},
});
在这部分代码中:
new { urlVar = currentUrl })';
currentUrl说:
在当前上下文中不存在;
我的问题是:
如何使currentUrl
在该特定位置有效?
否则,data:
部分没有错误? data: "{'urlVar':'"+ currentUrl
答案 0 :(得分:1)
此行中的问题是currentUrl
定义为客户端变量:
var currentUrl = window.location.href;
请注意,@Url.Action()
帮助程序是在服务器端执行的,您不能在其内部使用currentUrl
客户端变量作为操作参数(它不作为服务器端变量存在)。您需要使用如下查询字符串来重定向到GetData
操作方法中:
if (response != null && response.success) {
alert("Success");
// use query string here
window.location = '@Url.Action("GetData", "MyController")?urlVar=' + currentUrl;
}
如果要从服务器端获取URL,请修改Url.Action
助手以包括Request.Url
,Request.RawUrl
或Request.Url.AbsoluteUri
:
// alternative 1
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.AbsoluteUri })';
// alternative 2
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.ToString() })';
更新:
对于多个参数,您可以使用任一查询字符串参数:
window.location = '@Url.Action("GetData", "MyController")?urlVar=' + currentUrl + '&width=' + varwidthvalue + '&height=' + varheightvalue;
或者如果varwidthvalue
和varheightvalue
都是服务器端变量,则只需使用以下变量:
window.location = '@Url.Action("GetData", "MyController", new { urlVar = Request.Url.ToString(), width = varwidthvalue, height = varheightvalue })';