我在Ajax调用上遇到了一个错误400,我正在尝试使用JQUERY 2.2的实体框架在.NET Core 2.0中进行。
我的控制器方法看起来像这样:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult RetrieveDateCollections(string CollectionDate)
{
ViewData["CollectionTypeId"] = new SelectList(_context.Set<CollectionType>(), "CollectionTypeId", "CollectionTypeDescription");
ViewData["MemberId"] = new SelectList(_context.Member, "MemberId", "FullName");
var sPCC_Context = _context.Collection.Include(c => c.CollectionType).Include(c => c.Member);
return Json(sPCC_Context.ToListAsync());
}
和我的JavaScript如下:
function RetrieveDateCollections() {
var collectionDate = $('#CollectionDate').val().toString();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Collections/RetrieveDateCollections",
timeout: 40000,
data: JSON.stringify({ "CollectionDate": "12/10/2018" }),
dataType: "json",
done: function (data) {
alert("Success: " + response.toString());
},
fail: function (Result) {
alert("Error: " + Result.statusCode);
}
});
}
我从我的视图中称呼它:
<input type="date" asp-for="CollectionDate" class="form-control" onblur="RetrieveDateCollections();" />
我遇到以下错误:
在chrome
中当您沿着有问题的线钻取时,似乎是:
xhr.send( options.hasContent && options.data || null );
有什么想法?
您的代码无法验证抗试验性(因为您没有发送)。
您要么在控制器中删除[ValidateAntiForgeryToken]
标签,要么添加了一种在JavaScript中检索抗togergery手术的方法并将其发布。最简单的方法是以这种方式修改JS:
function RetrieveDateCollections() {
var collectionDate = $('#CollectionDate').val().toString();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Collections/RetrieveDateCollections",
timeout: 40000,
headers: { "RequestVerificationToken": getAntiforgeryToken() },
data: JSON.stringify({ "CollectionDate": "12/10/2018" }),
dataType: "json",
done: function (data) {
alert("Success: " + response.toString());
},
fail: function (Result) {
alert("Error: " + Result.statusCode);
}
});
}
function getAntiforgeryToken() {
// get the token from the form and return it
var token = $('input[name="__RequestVerificationToken"]').val();
return token;
}
为此,您需要在您的视图中包括一种抗试验性,因此:
@Html.AntiForgeryToken()