rwkiii
rwkiii

Reputation: 5846

Send JSON using Ajax in Querystring along with regular params

Is it possible to include a simple JSON string at the end of a querystring using Ajax GET? I'm using MVC and sending from the View to the Controller. In the Controller I want to be able to do this:

public class myObj
{
    public string Name { get; set; }
    public int Age { get; set; }
}

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetData(string Id)
{
    // Get querystring parameter
    string a = Request["a"];

    // Create typed object
    if (Request["myObj"] != null)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        myObj myobj = null;
        myobj = jss.Deserialize<myObj>(Request["myObj"]);
    }

    ...
}

In the View:

var myObj = '{ "Name" : "John", "Age" : "22" }';
$.ajax({
    type: "GET",
    url: "/GetData/?Id=" + $("#Id").val(),
    dataType: "json",
    data: {
        a: $('#a').val(),
        myObj: myObj
    },

    ...

});

I don't think my example above illustrates why I want to do this, but my question is whether or not this is possible. When the Ajax GET is executed myObj is always null in the Controller. I suspect it's because data: is creating a JSON already and myObj is not in the correct format, but I don't know how to fix this and can't seem to find an example showing how.

If this combination is possible can someone point me to where my code is wrong?

Upvotes: 0

Views: 1332

Answers (1)

Daniel Sanchez
Daniel Sanchez

Reputation: 263

Due to the amount of data you want to pass over (12 params) with potentially a lot of data, you may want to use POST rather than GET.

Examples of AJAX POST

var myObj= { "Name" : "John", "Age" : "22" }; //Array with similar properties to your Model

$.ajax({
    url : "/GetData/", 
    type: "POST",
    data : myObj,
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
    },
    error: function (jqXHR, textStatus, errorThrown)
    {

    }
});

and ensure that your Action is accepting the HTTP POST verb.

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GetData(string id, string a, myObj myObj)
{
}

See this reference for additional info.

Upvotes: 2

Related Questions