Rajmond Burgaj Rajmond Burgaj - 1 year ago 41
Ajax Question

How to pass complex JSON object in mvc action method?

I have a situation where I get data from ajax call. I want to call an action method and pass data as arguments. The data passed to action method should be mapped to object properties in parameter list.
Here is my class which is called FullQuestion.

public class FullQuestion : Question
public string Title { get; set; }
public string Content { get; set; }
public List<Tag> Tags { get; set; }

Here is my Ajax call method

var finalTagResultText = {Title: "title", Content: "content",Tag: { tagName: "tname", tagDescription: "tdesc"},Tag: { tagName: "tname1", tagDescription: "tdesc1"}};
url: '@Url.Action("AskQuestion", "Dashboard")',
type: "POST",
data: JSON.stringify(finalTagResultText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
window.location.href = "@Url.Action("Questions", "Dashboard")";

Here is my action method.

public void AskQuestion_Post(FullQuestion question)

I want to get the JSON object passed as a FullQuestion object. I used json2 library to make use of stingify method.
I get the title and content text but no Tag object.
Any idea how can i accomplish that ? Thanks in advance.

Answer Source

Your collection property is named Tags (not Tag) and since its a collection, you need to pass an array of Tag objects, for example

var finalTagResultText = { .... , Tags: [{ tagName: "tname", tagDescription: "tdesc"}, { tagName: "tname1", tagDescription: "tdesc1"}]}`

Side note: Your ajax success callback is redirecting to another page, in which case, do not use ajax to submit your data. The whole point of ajax is to stay on the same page. You would be better off just doing a standard submit and using a RedirectToAction() in your POST method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download