简体   繁体   中英

Populating a SelectList from a Database

I am completely new to using JSON data and ajax but I have a Select List I want populated from a web service. I have used fiddler to see that the web service is returning JSON data correctly and I verified that it is. The selectlist is only displaying the default ----Select-----

The code for the web service:

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

The Code for the 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>

Based on the comments above, I think the issue is that you're not accessing the array properly. Considering this JSON response:

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

If this is the value of data in your success function in the JavaScript code, then you can't loop through data as an array. Because data isn't an array, it's a single object. That object contains an array, in a property called d . Try changing your call to $.each() to use that property instead:

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

You might even test it with a normal for loop to make sure:

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

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