Reputation: 1071
I have a class defined like this:
// the Widget class has lots of properties I don't want to display
// so I use the displayWidget class to carry just what I want to display
public class displayWidget
{
public string WidgetId {get; set;}
public string Description {get; set;}
public displayWidget(Widget widget)
{
WidgetId = widget.WidgetId;
Description = widget.Description;
}
}
I have a ActionResult method that ends with::
var widgets = new List<displayWidget>();
foreach (var widget in matchingWidgets)
{
widgets.Add(new displayWidget(widget));
}
return Json(widgets);
My problem is, I don't know how to access the WidgetId and Description properties inside of my ajax .done handler:
.done(
function(response) {
$('#widgetSection').html('');
var html = '';
var jsonData = JSON.parse(response);
$.each(jsonData,
function (index, element)
{
$('body').append($('<div>', { text: element.WidgetId }));
$('body').append($('<div>', { text: element.Description }));
});
}
)
What should be inside of the .each function to output the WidgetId and Description?
Upvotes: 0
Views: 288
Reputation: 15934
Your ActionResult is returning an array, try:
element[0].WidgetId
This will return the first result, you can easily loop through the list if need be.
Edit
As @StephenMuecke mentioned, you don't need to use JSON.parse
here as you are returning JSON data already so something like this will suffice to loop through the results:
.done(
function(response) {
$('#widgetSection').html('');
$.each(response, function (index, element) {
$('body').append(
$('<div></div>').text(element.WidgetId )
)
});
}
)
Upvotes: 1