Search code examples
c#ajaxasp.net-coreasp.net-ajax

AJAX method won't pass parameter to a controller (C#)


I have tried like 10 solutions to make it work but it doesn't help. I'm trying to send parameter to a C# controller but everytime my parameter on controller side shows value of null.

Here is my code:

function createObject(x) {
    var obj = {};
    obj.Name = x;

    $.ajax({
        type: "POST",
        url: "/Home/Tire",
        data: JSON.stringify(obj),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            //failure  message
        }
    });
    function OnSuccess(response) {
        //do your stuff after success response
    }
}

And here comes controller:

[HttpPost]
public ActionResult Tire(string Name)
{
    string p = Name;
    return View("Tires");
}

Same thing happens when I try to pass value of x only.


Solution

  • I have tried like 10 solutions to make it work but it doesn't help. I'm trying to send parameter to a C# controller but everytime my parameter on controller side shows value of null.

    Actually, you are getting expected result that's null value in controller because based on your scenario, you have two options. Either, modify your asp.net core controller code or view javascript code.

    Way: 1 : If you modify controller code:

    If you want to keep your javascript code as it is in that scenario you would require to update your controller code and you need to introduce [FromBody] attribute and a custom class which will get you the expected result in your controller:

    Model:

    public class CustomModel
        {
            public string Name { get; set; }
        }
    

    Controller:

            [HttpPost]
            public ActionResult Tire([FromBody] CustomModel requestModel)
            {
                string p = requestModel.Name;
                return View("Tires");
            }
    

    View:

    Note: Through this way, No need to change anything within your view or javascript code snippet.

    Output:

    enter image description here

    Way: 2 : Modify javascript code:

    In this scenario, you would need to modify few things within your javascript code. You would need to get rid of contentType: "application/json; charset=utf-8", part from your request which would implement default request format that is application/x-www-form-urlencoded

    and then pass your object within data attribute of your request followed by controller parameter. As following:

     data: { YourControlleParameter: YourObjecet}
    

    In your scenarrio:

    data: { name: x }