Tom el Safadi
Tom el Safadi

Reputation: 6746

Asp.Net how to retrieve JSON from jQuery

I have created a JSON in jQuery which looks like this:

{  
   "objects":[  
      {  
         "ObjectId":1,
         "Line1":"Software",
         "Line2":"Microsoft",
         "Line3":"Web",
         "Line4":"Asp.Net",
         "Line5":"jQuery"
      },
      {  
         "ObjectId":2,
         "Line1":"Hardware",
         "Line2":"Microsoft",
         "Line3":"Computer",
         "Line4":"Surface",
         "Line5":"Pro"
      }
   ]
}

Now I use AJAX to send it via jQuery to my controller:

var postData = { objects: objectArray };

// Fire off the request to controller
$.ajax({
    cache: false,
    url: '/Controller/myAction',
    type: "POST",
    dataType: 'html',
    data: postData,
    success: function (result) {
        // success handler
    }
})


public ActionResult myAction(???)
{
    return view();
}

What I am not sure about is how I receive the object in my controller. Can someone help me with this please.

Thanks in advance!

Upvotes: 2

Views: 72

Answers (2)

Oleksandr Bilenko
Oleksandr Bilenko

Reputation: 175

Just a little lifehack for future: if you have to add new class based on existing JSON or XML model, there are awesome built-in tool in Visual Studio:

Class generating from JSON/XML models

Upvotes: 3

Nicholas J. Markkula
Nicholas J. Markkula

Reputation: 1562

This should work, start by creating a model object to represent the data on the server side

public class ObjectModel
{
    public string ObjectId { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string Line3 { get; set; }
    public string Line4 { get; set; }
    public string Line5 { get; set; }
}

Then define your mvc actions parameter like this

[HttpPost]
public ActionResult myAction(List<ObjectModel> objects)
{
    return view();
}

then simply pass the object array as json

// Fire off the request to controller
$.ajax({
    cache: false,
    url: '/Controller/myAction',
    type: "POST",
    contentType: "application/json",
    dataType: 'json',
    data: JSON.stringify(objectArray),
    success: function (result) {
        // success handler
    }
})

Upvotes: 2

Related Questions