skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. try this

    [HttpPost]
    [Route("Add")]
    public async Task Add(Service model) {
        //
    }
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. I get better results using the $.post() method of the jquery library
    here is an example:

    $.post(`Services/Add/?name=${name}&price=${price}&about=${about}`,
        function (insert) {
         if (insert) {
                    $('#result').fadeIn(200).html(insert).fadeOut(200, () => {
                        location. Reload()
                    })
                }
        });
    

    Source: JQuery Documentation about $.post()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search