2012-01-29 79 views
1

我有一个IEnumerable集合的自定义数据类型,我正在发送给客户端。 我想解析我的JQuery方法中的集合。目前我的价值为“未定义”。下面是我的代码:如何在JQuery中解析集合

服务:

[OperationContract] 
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] 
IEnumerable<CustomData> GetSetting(long userId); 

    public IEnumerable<CustomData> GetSetting(long userId) 
    { 
     var tempData = Context.DialogSettings.Where(item => item.id == userId).ToList(); 
     return tempData.Select(dialogSetting => new CustomData { KeyName = dialogSetting.KeyName, KeyValue = dialogSetting.KeyValue }).ToList(); 
    } 


[DataContract] 
public class CustomData 
{ 
    [DataMember] 
    public String KeyName; 
    [DataMember] 
    public String KeyValue; 
} 

客户:

function LoadSetting() { 
       $.ajax({ 
        type: "GET", 
        url: "SampleService.svc/GetSetting", 
        data: '{"userId": "' + 1 + '"}', 
        processData: true, 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (data) { 
         var myHistoryList = data.d; 
         alert(myHistoryList); // here I'm getting value: undefined 
        }, 
        error: function (result) { 
         alert('Service call failed: ' + result.status + '' + result.statusText); 
        } 
       }); 
      } 
     }); 
+3

你尝试过'提醒(数据)'吗? – georg 2012-01-29 10:34:36

+0

除了thg435的说法,如果你正在发送一个集合/列表,你会不会期望'data'是一个对象数组?你的ajax成功回调中'data.length'也未定义? – nnnnnn 2012-01-29 10:49:42

+1

为什么'data'有一个'd' var,如果它是一个列表??? – gdoron 2012-01-29 10:54:54

回答

2

从对问题的意见,我可以有把握地假定下面的js代码将工作:

if(typeof data != 'undefined'){ 
    alert(data[0].KeyName); //this will yield a value. 
} 
else 
    alert('Ok. This is weird'); 
+0

谢谢。您的解决方案在通过api 2控制器返回IEnumerable 时有效 – ModChowdhury 2017-05-15 12:33:42