Search code examples
c#ajaxasp.net-mvc-controller

mvc controller pameter getting null value in ajax call


I am making ajax call like this

 deleteAge(item: any): string {

           $.ajax({
                method: "POST",
                url: 'DeleteAge',
                data: item.Id(),
                success: (response) => {
                    toastr.success("ready soon");
                },
                error: (event) => {
                    toastr.error("Error occured ");
                }
            }).always(() => {

                });


        return "";


    }

Here is my method in controller which is currently nothing almost implemented

 [HttpPost]
    public ActionResult DeleteAge(string id)
    {
        throw new Exception();
    }

when i run the code then in my controller i dont get any id.. its null. when i debug my javascript code then this code item.Id() is not blank. Even if i pass hardcoded value to data in ajax call still controller gets null. What is wrong?


Solution

  • Rather than using:

    data: item.Id(),
    

    I'd suggest using:

    data: { id: item.Id()},
    

    This way the id value is associated with the id name - allowing model binding to work correctly.