0

I'm trying to call API controller method using ajax and passing some parameters. The api method is getting called but values are coming as null in controller method.

Using same ajax call, another controller (not api controller) having same method receives parameter values and returns results but i'm stuck with passing values to api controller method. Kindly help

 $(document).ready(function ()
                {
                    $("#DropDownName").change(function ()
                    {
                        $.ajax({
                            type: "POST",
                            dataType: "text",
                            url: "@(Url.Action("SampleAction", "XYZController"))",
                            data: {
                                "param1": $("#DropDownName :selected").val(),
                                "param2": $("#input2").val(),
                                "param3": $("#input3").val()
                            },

                            success: function (response) {

                            document.getElementById("result").textContent = "Result: " + response;
                        },


                        });
                    }); 
                });

API Controller Method

    [Route("api/[controller]")]
    [ApiController]
    public class XYZController : ControllerBase
    {
        [ActionName("SampleAction")]
        [HttpPost]
        public decimal SampleAction(string dropdownselectedvalue,decimal input2, int input3)
        {
         //code here - This method is getting called but getting null parameter values
        }
    }

1 Answer 1

1

Change your ajax like below:

data: {
        "dropdownselectedvalue":$("#DropDownName :selected").val(),
        "input2": $("#input2").val(),
        "input3": $("#input3").val(),
},

Be sure add FromForm in your backend code:

[Route("api/[controller]")]
[ApiController]
public class XYZController : ControllerBase
{
    [ActionName("SampleAction")]
    [HttpPost]
    public decimal SampleAction([FromForm]string dropdownselectedvalue,
        [FromForm] decimal input2, [FromForm] int input3)
    {
        return input2;
        //code here - This method is getting called but getting null parameter values
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

[FromForm] made it work. First part was right in actual code. I have put some dummy names for parameters here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.