2

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!

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's freaking awesome, I've been using json2csharp.com for the longest time and never knew this was already baked into VS
2

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
    }
})

3 Comments

Thanks for your answer I will try it out. I slightly edited my question. Are you missing ObjectId in the model?
Worked successfully:) !!
Sweet! glad to help =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.