如何在JQuery中解析集合

时间:2012-01-29 10:29:00

标签: javascript jquery asp.net

我有一个我正在发送给客户端的IEnumerable Custom DataType集合。 我想在我的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);
                    }
                });
            }
        });

1 个答案:

答案 0 :(得分:2)

从问题的评论中我可以安全地假设以下js代码可以工作:

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