-2

我使用的是 html 下拉菜单,而不是 asp .net 控件。我想使用 jquery 在下拉列表中填充数据库中的员工姓名。我必须在 aspx.cs 文件中编写什么代码。以及如何绑定 json 数据?请回复

My code is

 <script type="text/javascript" language="javascript">
 $(document).ready(function()
 {
 $().ready(function(){
 $.ajax({
 type:"POST",
 data:"{}",
 url:"TestJson.aspx/GetName",
 dataType:"json",
 success:function(msg)
 {
 var dropDown=$("#ddlName");
 dropDown.append($("<option></option>").val('').text('- Select -'));

$.each(data, function () {
    dropDown.append($("<option></option>")

        .text($(this).attr("Name")));
 });
 },
 error:function()
 { 
 alert("failed to load");
 }
 });
 });

  </script>
  <style type="text/css">

    #ddlName
    {
        width: 146px;
    }
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="border:1px solid gray; width:400px;">



                    Name

                    <select id="ddlName">
                    <option value="">--Select--</option>
                </select>
        </div>
</form>




My .cs code

  public  static Details[] BindDropdown()
{
 DataTable dt = new DataTable();
    List<Details> details = new List<Details>();

    SqlConnection con = new SqlConnection("Data Source=ST0022;Initial     Catalog=QuickMove_Globe;User ID=sa;Password=good");

       SqlCommand cmd = new SqlCommand("SELECT ClientBranchID,Name FROM     ProspectiveLead", con);

            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            foreach (DataRow dtrow in dt.Rows)
            {
                Details detail = new Details();
                detail.Id = Convert.ToInt32(dtrow["ClientBranchId"].ToString());
                detail.Name = dtrow["Name"].ToString();
                details.Add(detail);
            }


    return details.ToArray();
}
public class Details
{
    public int Id { get; set; }
    public string Name { get; set; }
}
4

1 回答 1

0

在 .aspx 页面代码中

   <select id="ddlStateName"><option value="0" selected="selected">State</option>
   </select>  

在 Web 服务中,我们有以下方法

为状态创建通用类

public class StateProperty
    {
      public int StateId { get; set; }
      public string StateName { get; set; }

    }



public List<StateProperty> GetAllState()
      {
          _objDataWrapper=new DbWrapper(Common.CnnString,CommandType.StoredProcedure);
          var objStateList = new List<StateProperty>();
          _dataSet=new DataSet();
          try
          {
              // Here you will write query like "select * from state" and fill it dataset
              _dataSet = _objDataWrapper.ExecuteDataSet("Aj_Proc_GetStateList");
              objStateList = BindStateObject(_dataSet.Tables[0]);
          }
          catch (Exception ex)
          {


          }
          return objStateList;
      }

   //BindStateObject method defined here 

 private List<StateProperty>BindStateObject(DataTable dataTable)
      {
          var objStateList = new List<StateProperty>();

          try
          {
              if(dataTable.Rows.Count>0)
              {
                  for(var j=0;j<dataTable.Rows.Count;j++)
                  {
                      var objState = new StateProperty
                                         {
                                             StateName = Convert.ToString(dataTable.Rows[j]["AjStateName"]),
                                             StateId = Convert.ToInt32(dataTable.Rows[j]["AjStateId"])
                                         };
                      objStateList.Add(objState);
                  }
              }
          }
          catch (Exception ex)
          {


          }
          return objStateList;
      }

     [WebMethod]
   public ListItem[] GetAllState()
   {
       var data = GetAllState();
       if (data.Count > 0)
           return data.Select(result => new ListItem()
           {
               Text = result.StateName,
               Value =
                   result.StateId.ToString(CultureInfo.InvariantCulture)

           }).ToArray();
       return null;
   }

然后我们必须通过 Jquery 调用这个 web 方法

function BindState() {
    var countryId = countryObj.val();

        $("#ddlStateName").empty().append('<option selected="selected" value="0">Select State</option>');
        $.ajax({
            type: "POST",
            url: "pathofyourwebservice/GetState",
            async: true,
            data: '{""}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                PopulateControl(response.d, stateObj);

            },
            error: function (xml, textStatus, errorThrown) {
                alert(xml.status + "||" + xml.responseText);
            }
        });
    } 
}

//这里我定义了PopulateControl

function PopulateControl(list, control) {

    if (list.length > 0) {

        control.removeAttr("disabled");

        $.each(list, function () {

            control.append($("<option></option>").val(this['Value']).html(this['Text']));

        });
    }
    else {
        control.empty().append('<option selected="selected" value="0">Not available<option>');
    }
}

然后在document.ready函数侧的页面上调用此方法

$(document).ready(function () {
  BindState();
});
于 2012-10-26T12:21:29.803 回答