0

I'm sending a value through JQuery to an MVC HttpPost action method, but instead it is getting a null value. When I send a plain string it works fine, but when I send an array it gets the null value. Here is the code.

code to send the value

function Submit() {
        var QSTR = {
            name: "Jhon Smith",
            Address: "123 main st.",
            OtherData: []
        };
        QSTR.OtherData.push('Value 1');
        QSTR.OtherData.push('Value 2');

        $.ajax({
            type: 'POST',
            url: '/Omni/DoRoutine',
            data: JSON.stringify({ obj: 'Reynor here!' }),
            // this acctually works
            // and at the action method I get the object[] 
            // with object[0] = 'Reynor here!'
            // but when I use the object I really need to send I get null
            data: JSON.stringify({ obj: QSTR }), //I get null
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            success: function (msg) {
                alert('ok');
            },
            error: function (xhr, status) {
                alert(status);
            }

        });
    }

this is the action method code:

            [HttpPost]
        public ActionResult DoRoutine(object[] obj)
        {
            return Json(null);
        }

What is the solution for this and why is this happening? thanks

Overlord
  • 2,740
  • 2
  • 18
  • 22

1 Answers1

0

QSTR is a complex type, so you need complex data in your post method.

public class QSTR
{
    public string name { get; set; }
    public string Address { get; set; }
    public object[] OtherData { get; set; }
}

[HttpPost]
public ActionResult DoRoutine(QSTR obj)
{
    return Json(null);
}

But if you want receive only array of otherdata you should send only in in your ajax:

 $.ajax({
    data: JSON.stringify({ obj: QSTR.OtherData }),
    // other properties
 });
aleha_84
  • 8,309
  • 2
  • 38
  • 46
  • I understand that would a possible solution, but I still don't get why. I had a similar method on asp.net, actually it was a [WebMethod], and following my initial approach it worked fine, I mean I got my object[] parameter. Why it doesn't work with an [HttpPost] method on MVC? What if this info I want to send back to the server would mean a different data structure depending on several factors? thanks – Overlord Sep 26 '14 at 20:39
  • @Overlord maybe [this](http://stackoverflow.com/questions/9067344/net-mvc-action-parameter-of-type-object) can help – aleha_84 Sep 26 '14 at 21:26
  • thanks aleha, your answer was very helpful in finding my solution – Overlord Sep 27 '14 at 14:51