基本上
@Html.ActionLink()
帮助器呈现定位标记(
<a>
)使用属性并默认为通过刷新整个页面来使用get请求,因此需要添加
preventDefault()
以便使用该元素的Ajax回调。如果action方法使用http get方法,则可以对锚链接的公共类执行简单的Ajax调用,如下所示:
$('.text-info').on('click', function (e) {
e.preventDefault();
var url = $(this).attr('href');
$.get(url, function (response) {
// do something with AJAX response
});
});
但是,由于目标控制器操作标记为
[HttpPost]
,需要从中提取查询字符串参数
href
带有附加函数的属性,并在Ajax调用中使用它们
type: 'POST'
设置或使用
$.post()
:
$('.text-info').on('click', function (e) {
e.preventDefault(); // mandatory to prevent GET request
var url = $(this).attr('href');
var pcs = getQueryStringParams(url, 'ProductCodeScheme');
var pc = getQueryStringParams(url, 'ProductCode');
var sn = getQueryStringParams(url, 'SerialNumber');
var batch = getQueryStringParams(url, 'Batch');
var expDate = getQueryStringParams(url, 'ExpirationDate');
var csc = getQueryStringParams(url, 'CommandStatusCode');
// create key-value pair for action method parameters
var obj = { ProductCodeScheme: pcs, ProductCode: pc, SerialNumber: sn, ... }
$.ajax({
type: 'POST',
url: url.split('?')[0], // URL without query string, or use '@Url.Action("VerifyPack", "Home")'
data: obj,
dataType: 'json', // expects response as JSON
success: function (response) {
// do something with AJAX response
},
error: function (xhr, status, err) {
// error handling
}
});
// just make sure that the link is not redirecting
return false;
});
function getQueryStringParams(url, name) {
return (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1];
}
实际上,还有另一种方法可以从锚标记调用Ajax,比如
@Ajax.ActionLink()
,取决于您的选择:
@Ajax.ActionLink("Verify Pack", "VerifyPack", "Home", new { ProductCodeScheme = @item.ProductCodeScheme, ProductCode = @item.ProductCode, SerialNumber = @item.SerialNumber, Batch = @item.Batch, ExpirationDate = @item.ExpirationDate, CommandStatusCode = 0 },
new AjaxOptions { HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "targetElementId",
OnComplete = "onComplete();"
},
new { @class = "text-info" })
注:
如果需要处理来自同一个控制器的Ajax请求和普通请求,可以使用
Request.IsAjaxRequest()
(或)
Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest"
在核心MVC中。