从asp获取html中的dropdownlist数据

时间:2015-11-13 10:52:52

标签: javascript c# jquery html asp.net

我希望使用html(客户端)下拉列表获取asp(服务器端)的值。 当点击html中的dropdownlist按钮时,它应该加载asp值,而我的大四学生说使用网络方法,但我不知道网络服务,有没有可能解决这个问题?

asp(从数据库获取数据)

public void BindDropDownListData(){
   string cs = "server=.;uid=sam;pwd=p@ssw0rd;database=SSP";
   using (SqlConnection con = new SqlConnection(cs)){
      try{
           con.Open();
           SqlCommand cmd = new SqlCommand("select PCode,PName from SMSQUARE", con);
           SqlDataAdapter sda = new SqlDataAdapter(cmd);
           DataTable dt = new DataTable();
           sda.Fill(dt);
           ddlprojects.DataSource = dt;
           ddlprojects.DataTextField = "PrjName";
           ddlprojects.DataValueField = "prjcode";
           ddlprojects.DataBind();
       }
       catch (Exception e){
          Response.Write(e.Message.ToString());
       }  

以上数据我想加载html dropdownlist

以下

html

<td>
    <select name="ddlProjects" id="ddlProjects" tabindex="1" onchange="ddlProjects_SelectedIndexChanged" class="dropdown"></select>
</td>

1 个答案:

答案 0 :(得分:0)

首先将使用System.Web.Services 添加到命名空间 将下一个代码添加到aspx页面中,然后添加jquery引用:

$("#ddlProjects").click(function () {
    var adID = $('#cphRateAd_hidden_adv_id').val();
    $.ajax({
        type: "POST",
        url: "CodeBehind.aspx/Method",
        data: "{param: '" + 1}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            //some actions if you need
        },
        error: function (data) {
            alert('Can not load values');
        }
    });
});

CodeBehind.aspx是您的代码隐藏页面,Method是您处理数据的方法。在你的方法背后的代码将是

[WebMethod]
public static void BindDropDownListData(int param)
{//param is for nothing,     just parameter
    string cs = "server=.;uid=sam;pwd=p@ssw0rd;database=SSP";
    using (SqlConnection con = new SqlConnection(cs))
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select PCode,PName from SMSQUARE", con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            ddlprojects.DataSource = dt;
            ddlprojects.DataTextField = "PrjName";
            ddlprojects.DataValueField = "prjcode";
            ddlprojects.DataBind();
        }
        catch (Exception e)
        {
            Response.Write(e.Message.ToString());
        }
    }
}