[英]I can't get data from AJAX post request in C# controller
我想使用 ajax 將數據從 javascript 發送到 c# controller,但是當我的 controller 中的 Add 方法被調用時,它的所有 arguments 都是 null
AJAX:
function addRequest(name, price, about){
$.ajax({
url: 'Services/Add',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: {
'name' : name ,
'price' : price,
'about' : about,
},
dataType: "json",
success: (insert) => {
if (insert) {
$('#result').fadeIn(200).html(insert).fadeOut(200, () => {
location.reload()
})
}
}
})
}
我的 controller:
[ApiController]
[Route("[controller]")]
public class ServicesController: Controller
{
[HttpPost]
[Route("Add")]
public async Task Add(string? name, string? price, string? about)
{
await Context.Services.AddAsync(new Service
{
Name = name,
Price = price,
About = about
});
await Context.SaveChangesAsync();
}
}
嘗試這個
[HttpPost]
[Route("Add")]
public async Task Add(Service model) {
//
}
檢查你的controller是否被授權。 如果您希望 controller 在沒有任何授權的情況下工作,那么您必須在 controller 上添加 allowannoymous 屬性,因為在 ajax 調用中沒有提供訪問令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.