简体   繁体   中英

Accessing fields in a JSON response

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM