Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting object with list of ints from jquery to .net mvc 3 controller

I'm having difficulty posting a JavaScript object via jQuery to a .net MVC 3 controller.

My object:

var postData = {
    'thing1' : "whatever",
    'thing2' : "something else",
    'thing3' : [1, 2, 3, 4]
}

My jQuery Call:

$.post('<%= Url.Action("Commit", "MassEdit") %>', postData, function (data) {
    // stuff
});

My View Model:

public class SubmitThing {
    public string thing1 { get; set; }
    public string thing2 { get; set; }
    public IEnumerable<int> thing3 { get; set; }
}

My controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Commit(SubmitThing changes)
{
    return new EmptyResult();
}

The problem is that my 'changes' object that I have within my controller have thing1 equal to "whatever", thing2 equal to "something else", but thing3 is null. Now do I get thing3 to be my list of integers?

Added: I think this is more of a mapping issue than a serialization issue. In my controller, if I look at

HttpContext.Request.Form["thing3[]"]

I get a string with the value of "1,2,3,4". But again, I'd like the mapping to just work.

Thanks!

like image 642
Erik W Avatar asked Jun 15 '11 16:06

Erik W


1 Answers

Just post it as json:

    $.ajax({
        url: '<%= Url.Action("Commit", "MassEdit") %>',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({'thing1' : "whatever",
    'thing2' : "something else",
    'thing3' : [1, 2, 3, 4]
}),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

        }
    });

and it should work

like image 148
ryudice Avatar answered Oct 15 '22 03:10

ryudice