I want to send data from javascript to c# controller using ajax, but when the Add method in my controller is called all its arguments are 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()
})
}
}
})
}
My 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();
}
}
CodePudding user response:
I think binding of this controller in not working, you are sending object by ajax but you are expecting three separte primitives
try:
[HttpPost]
[Route("Add")]
public async Task Add(Service service)
{
await Context.Services.AddAsync(service);
}
or try adding setup binding attributes
CodePudding user response:
try this
[HttpPost]
[Route("Add")]
public async Task Add(Service model) {
//
}
CodePudding user response:
Check if your controller is authorized or not. If you want the controller to work without any authorization then you have to add allowannoymous attribute on your controller since no access token is given in the ajax call.