是否可以从web方法返回列表<string>并传递返回值以使用jquery绑定html选择?</string>

时间:2011-04-28 03:39:29

标签: c# jquery asp.net ajax

我试图绑定一个html选择,我为此编写了一个webmethod,它返回一个列表。我如何使用此返回值来使用jquery绑定我的选择控件....?我被困了......代码附在此处:

function columnDropdownScript() {
  var reqTableNameParameter = "Designation";  //$('#ddlTableNames').text;
  var requestTableParameters = '{' +
                        'selTableName:"' + reqTableNameParameter + '"}';
  // Configure AJAX call to server                        
  $.ajax({
    type: "POST",
    url: "Webtop.aspx/FillColumnDropdown",
    data: requestTableParameters,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: DisplayColumnNames, //Event that'll be fired on Success
    error: DisplayError //Event that'll be fired on Error
  });

}
function DisplayColumnNames(serverResponse) {

  $("#ddlColumnNames").get(0).options.length = 0;
  $("#ddlColumnNames").get(0).options[0] = new Option("Select", "-1");
  $.each(serverResponse.d, function(index, item) {
    $("#ddlColumnNames").get(0).options[$("#ddlColumnNames").get(0).options.length] = new Option(item.Display, item.Value);
  });
  alert('Check Column DropDown');
}




 [WebMethod]
    public static List<string> FillColumnDropdown(string selTableName)
    {
        int x=1;
        string selectedTable = selTableName;
        List<string> columnsToBind = new List<string>();
        foreach (Columns column in Metadata.columnsOfSelectedTables)
        {
            if (column.TableName.Equals(selectedTable))
            {
                columnsToBind.Add(column.ColumnName);
            }
        }
       return columnsToBind;
    }

2 个答案:

答案 0 :(得分:2)

//我没有测试过这个问题,但是从我的头脑中开始,这应该可以解决问题 //(注意,这会附加到列表中。如果多次调用,您可能需要清除)

$.ajax({
    type: "POST",
    url: "Webtop.aspx/FillColumnDropdown",
    data: requestTableParameters,
    //contentType: "plain/text",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        for (var i = 0, l = msg.length; i < l; i++) {
            $("#the_selectbox").append("<option>" + msg.d[i] + "</option>");
        }
    },
    error: DisplayError //Event that'll be fired on Error
  });

答案 1 :(得分:0)

只是出于好奇,你为什么要为它做一个web方法而不是添加onload / postback触发器?

你在哪里将你的列表投射到代码背后的json?难道它的返回类型不是xml吗?

无论如何,jQuery对象属性要求匿名函数:

$.ajax({
    // ...
    success:function(serverResponse){
        //success code
    },
    error:function(serverResponse){
        //error code
    },
});