asp.net core 通过ajax调用后台方法(非api)

时间:2023-12-17 15:39:26

1、    在Startup.cs文件中添加:        services.AddMvc();
            services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

2、在cshtml 文件中添加:

@Html.AntiForgeryToken()

@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

3、前端代码

$('#btnPost').on('click', function () {
var item1 = $('#txtItem1').val();
var item2 = $('#txtItem2').val();
$.ajax({
type: "POST",
url: "RoleMenu?handler=Send",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
id: item1,
name: item2,
}), contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dvItems = $("#dvPostItems");
dvItems.empty();
$.each(response, function (i, item) {
var $tr = $('<li>').append(item).appendTo(dvItems);
});
},
failure: function (response) {
alert(response);
}
});

后台代码:

public ActionResult OnPostSend()
{
string sPostValue1 = "";
string sPostValue2 = "";
{
MemoryStream stream = new MemoryStream();
Request.Body.CopyTo(stream);
stream.Position = ;
using (StreamReader reader = new StreamReader(stream))
{
string requestBody = reader.ReadToEnd();
if (requestBody.Length > )
{
var obj = JsonConvert.DeserializeObject<TmpRoleMenu>(requestBody);
if (obj != null)
{
sPostValue1 = obj.id+"postdata";
sPostValue2 = obj.name+"postdata";
}
}
}
}
List<string> lstString = new List<string>
{
sPostValue1,
sPostValue2,
};
return new JsonResult(lstString);
}

参考:

1、http://www.jb51.net/article/133437.htm