ShaneKm
ShaneKm

Reputation: 21368

MVC bind Json collection of objects to controller action

is there a way to send a collection of objects to MVC action?

View:

        $(".iconDocumentText").click(function (e) {
            e.preventDefault();
            var $inputs = $("form.form :input:not('.submit')");
            var values = {}; // get search form values
            $inputs.each(function () {
                if ($(this).val()) {
                    values[this.name] = $(this).val();
                }
            });
            console.log(JSON.stringify(values));
            $.ajax({
                url: "@Url.Action("Export","Log")",
                data: JSON.stringify(values),
                contentType: 'application/json',
                type: 'GET',
                success: function (data) {
.........
                }
            });
        });

I tried this without any luck:

    public ActionResult Export(Dictionary<string, string> values)
    {
....

this is what's being sent to controller action:

{"f_device":"4","f_package":"AGI-VS-GAME-M52-1.5.3.2.67"}

Upvotes: 2

Views: 749

Answers (1)

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

You have also to indicate that it is of datatype json and pass them directly:

Script :

$.ajax({
    url: "@Url.Action("Export","Log")",
    data: values,
    contentType: 'application/json',
    type: 'GET',
    dataType: 'json'
});

Controller :

public ActionResult Test(int f_device, string f_package)
{

EDIT :

But if you want to retrieve a dictionary, you can encapsulate your data in an object :

Script :

$.ajax({
    url: "@Url.Action("Export","Log")",
    data: { values : values },
    contentType: 'application/json',
    type: 'GET',
    dataType: 'json'
});

Controller :

public ActionResult Test(Dictionary<string, string> values)
{

Upvotes: 4

Related Questions