iShareHappyCode
iShareHappyCode

Reputation: 255

How do I POST collection of data to controller action

I have following code to send DATA to controller action and return the plain HTML I am getting empty object in controller action.

        var employees = [
                       { Title: "John", DataType: 1 },
                       { Title: "Anna", DataType: 2 },
                       { Title: "Peter", DataType: 3 }
    ];

    $("#btn-continueedit").click(function () {
        $.ajax({
            type: 'POST', // I tried post also here
            cache: false,
            url:'/user/UserinfoWizard',
               data: { values: employees }, 
            success: function (data) {

                $("#editUserInfo").html(data);

            }
        });
        return false; 
    });

Here is my controller action

             [HttpPost]
         public ActionResult UserInfoWizard(List<UserInfoEditDetail> values)
            {
             // I get empty object 'values' here :( 
            }

Upvotes: 0

Views: 511

Answers (2)

Sai Avinash
Sai Avinash

Reputation: 4753

$("#btn-continueedit").click(function () {
        $.ajax({
            type: 'GET', // I tried post also here
            cache: false,
            dataType:JSON,
            url:'/user/UserinfoWizard',
            data: JSON.stringify({ data:getSelectedAttributes()}),
            success: function (data) {

                $("#editUserInfo").html(data);

            }
        });
        return false; 
    });

Updated:

When you are passing data during an ajax call, it should be in the form of an object and not an array

Upvotes: 0

devqon
devqon

Reputation: 13997

The data passed with the ajax call should be an object containing the parameter which you want to use in the controller action. Your action expects a values parameter passed with the data, so your data object should be data: { values: getSelectedAttributes() }

JavaScript:

$("#btn-continueedit").click(function () {
    $.ajax({
        type: 'POST',
        //..
        data: { values: getSelectedAttributes() }, //Use the data object with values
        //..
    });
    return false; 
});

C#:

[HttpPost]
public ActionResult UserInfoWizard(object values) // parameter name should match the name passed in data object
{
   //..
}

EDIT

Indeed you action expects an object, while your values is an array. I don't know what the values are, but in your action you should have the int[] values or string[] values as parameter or any other array type you are expecting.

Upvotes: 2

Related Questions