从数据库填充SelectList

时间:2013-09-16 15:13:23

标签: c# jquery asp.net json webforms

我对使用JSON数据和ajax完全不熟悉,但我有一个我希望从Web服务填充的选择列表。我已经使用fiddler看到Web服务正确地返回JSON数据,我确认它是。选择列表仅显示默认的----Select-----

网络服务的代码:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]

 [ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    private TrackerEntities db = new TrackerEntities();


    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetCompanies()
    {
        var companies = new List<Company>();
        companies = (from c in db.Ref_Company
                     select new Company { CompanyDesc =  c.CompanyDesc,CompanyCode = c.CompanyCode }).ToList();
        return new JavaScriptSerializer().Serialize(companies);
    }


}

public class Company
{
    public string CompanyCode { get; set; }
    public string CompanyDesc { get; set; }
}

HTML代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>   
<script type="text/javascript">
 $(document).ready(function () {
     $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         data: "{}",
         url: "WebService1.asmx/GetCompanies",
         dataType: "json",
         success: ajaxSucceess,
         error: ajaxError
     });
     function ajaxSucceess(data) {
        $.each(data, function (index, elem) {
           // Create a new <option>, set its text and value, and append it to the <select>
           $("<option />")
              .text(elem.CompanyCode)
              .val(elem.CompanyDesc)
              .appendTo("#Select1");
        });
     }

     function ajaxError(response) {
         alert(response.status + ' ' + response.statusText);
     }
 });


</script>   
</head>
<body>
<form id="form1" runat="server">


 <select id="Select1"><option>---Select------</option></select>


</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

根据上面的评论,我认为问题是你没有正确访问数组。考虑到这个JSON响应:

{ "d" : "[
  { "CompanyCode" : "HTH", "CompanyDesc" : "Company1" },
  { "CompanyCode" :‌ "SMC", "CompanyDesc" : "Company2" },
  { "CompanyCode" : "CTT", "CompanyDesc" : "‌​Company3" }
]"}

如果这是JavaScript代码中成功函数中data的值,则无法将data作为数组循环。因为data不是数组,所以它是单个对象。该对象在名为d的属性中包含数组。尝试将您的通话更改为$.each()以改为使用该属性:

$.each(data.d, function (index, elem) {
    //...
});

您甚至可以使用正常的for循环对其进行测试,以确保:

for (var i = 0; i < data.d.length; i++) {
    // do something with data.d[i]
}