Reputation: 1119
I want to pass a complex object from a Controller Method back to my Ajax call. As far as I know from several researches JSON is the thing of choice at this point.
Here's my Controller Method:
public JsonResult GetUserByData(string fn, string ln, string dep, string cc, string tel, string mail) {
IList<Models.Person> userCollection = Models.Person.GetPersonsByData(fn, ln, dep, tel, cc, mail).ToList();
if (userCollection.Count > 1) {
return Json(new { Complex= true, HTML = PartialView("SomeView.cshtml", userCollection) });
}
else {
return Json(new { Complex = false, HTML = PartialView("SomeOtherView.cshtml", userCollection.First()) });
}
Here's my Ajax call:
$.ajax({
url: 'Home/GetUserByData',
type: 'POST',
dataType: 'html',
data: {
fn: firstname,
ln: lastname,
dep: department,
cc: costcenter,
tel: telephone,
mail: mail
},
success: function (data) {
if (data.Complex)
$('#Customer_Person').html(data.HTML);
else
$('#Notification_Area').html(data.HTML);
}
});
Back in my Script it seems that the Properties "Complex" and "HTML" can not be accessed - What am I doing wrong? Is this the best approach passing complex objects or are there other ways doing this?
Upvotes: 0
Views: 50
Reputation: 36511
Since you are specifying the return type as HTML (dataType: 'html'
), jQuery is treating the response as a string (and not JSON), so data.Complex
won't evaluate to anything. If you were to try to parse the data as JSON it would likely error out as HTML and JSON don't play very well together. I would suggest returning the JSON first and making a subsequent call for the HTML or just selecting the correct template on the server and only sending the HTML.
edit: @Savaratkar is correct, you could also encode/escape your HTML and pass it via JSON.
Upvotes: 3