2014-11-08 138 views
0

我有一个类定义是这样的:访问字段

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

我有与::结束的ActionResult的方法

var widgets = new List<displayWidget>(); 
foreach (var widget in matchingWidgets) 
{ 
    widgets.Add(new displayWidget(widget)); 
} 
return Json(widgets); 

我的问题是,我不知道如何访问为widgetid和Description属性我的AJAX .done处理程序的内部:

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

应该是。每次的F里面有什么unction输出WidgetId和Description?

+0

什么element.WidgetId/element.Description返回? – malkam 2014-11-08 16:46:37

+0

我不知道...我知道该响应包含我期望它,但现在JSON.parse(响应)返回错误0x800a03f6 - JavaScript运行时错误:无效字符 – davecove 2014-11-08 17:39:17

+2

不'用户JSON.parse。尝试$ .each(response,function(){}); – malkam 2014-11-08 17:41:13

回答

1

你的ActionResult被返回一个数组,尝试:

element[0].WidgetId 

这将返回的第一个结果,你可以很容易地遍历列表如果需要的话。

编辑

正如@StephenMuecke提到的,你不需要使用JSON.parse这里你正在返回JSON数据已经所以像这样将通过的结果足以循环:

.done(
    function(response) { 
     $('#widgetSection').html(''); 
     $.each(response, function (index, element) { 
      $('body').append(
       $('<div></div>').text(element.WidgetId) 
      ) 
     }); 
    } 
) 
+0

这不是真的有必要。所有需要的都是'$ .each(response,function(index,element){$('body')。append($('

').text(element.WidgetId))});'响应值已经JSON,所以它不应该被解析 – 2014-11-09 02:17:14

+0

同意,但他的问题是如何访问数据,这就是我已经解释。我认为如果他知道这是一个数组(我已经解释过),那么他可以从那里继续使用它。尽管为了使其他用户清楚起见,我会用这些信息更新答案。 – webnoob 2014-11-09 09:47:56