Abhilash V
Abhilash V

Reputation: 329

Data from ajax post is passing null to the controller

AJAX call - 

Here countryId is passed as "AU" for example -

$("#Countries").change(function () {
        var countryId = this.value;
        $.ajax({
            url: '/Registers/GetStates',
            type: "POST",
            data: { 'data': countryId },
            success: function (states) {
                $("#States").html(""); // clear before appending new list 
                $.each(states, function (i, state) {
                    $("#States").append(
                        $('<option></option>').val(state.Id).html(state.Name));
                });
            }
        });
    });

After calling the GetStates method 'countryId' is always passed as null in the controller method. Not sure what I'm missing here. I tried JSON.Stringify({ 'data': countryId }) also. Can anyone help me out ?

Controller Action - 

[HttpPost]
public SelectList GetStates(string countryId)
{
     return Helper.GetStates(countryId);
}

Upvotes: 2

Views: 5517

Answers (1)

Anadi
Anadi

Reputation: 754

The parameter in your action method should be exactly same as the parameter name in the 'data' option of ajax.

In your case it is 'countryId'

[HttpPost]
public SelectList GetStates(string countryId)
{
     return Helper.GetStates(countryId);
}

Change your ajax data option accordingly.

data: { countryId: countryId },

It will work.

Upvotes: 6

Related Questions