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();
}
}
5
Answers
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.
try this
I think binding of this controller in not working, you are sending object by ajax but you are expecting three separte primitives
try:
or try adding setup binding attributes
Try using a service class to receive the JSON rather using distinct values.
Follow below links to learn more.
https://www.aspsnippets.com/Articles/Pass-Send-Model-object-in-jQuery-ajax-POST-request-to-Controller-method-in-ASPNet-MVC.aspx
https://www.c-sharpcorner.com/article/asp-net-mvc-how-to-use-ajax-with-parameters/
I get better results using the $.post() method of the jquery library
here is an example:
Source: JQuery Documentation about $.post()