我在asp .net中创建了一个页面,在其中添加了jquery引用,并在另一台服务器上托管了Web服务。我有使用jQuery绑定的下拉列表,但它没有得到绑定,我也无法识别错误是什么。我的代码。
<script src="Script/jquery-1.7.1.min.js" type="text/javascript"></script>
<table>
<tr>
<td>
<asp:DropDownList ID="ddl" runat="server">
</asp:DropDownList>
<asp:HiddenField ID="hf" runat="server" />
</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#ddl').append(
$('<option></option>').val('0').html('Please Wait...')
);
$.ajax({
url: "http://***.*.1.165:91/MastersService.asmx/GetDocTypeList",
data: "{}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
// for get selected value from code behind
$('#ddl').change(function () {
$('#hf').val($('#ddl').val());
});
});
function OnSuccess(data) {
$('#ddl').empty();
var d = data.d;
var dropdown = $('#ddl');
for (var i = 0; i < d.length; i++) {
dropdown.append(
$('<option></option>').val(d[i].docCode.toString()).html(d[i].docName.toString())
);
}
//for keep data after postback
$('#ddl').val($('#hf').val());
}
function OnError() {
alert("Failed!");
}
</script>
WEBMETHOD ..
[System.Web.Script.Services.ScriptService]
public class MastersService : System.Web.Services.WebService
{
[WebMethod]
public List<DocType> GetDocTypeList()
{
DataTable dt = MM.DocumentTypeList();
List<DocType> doctype = new List<DocType>();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DocType objst = new DocType();
objst.docCode = Convert.ToString(dt.Rows[i]["docCode"]);
objst.docName = Convert.ToString(dt.Rows[i]["docName"]);
doctype.Insert(i, objst);
}
}
return doctype;
}
}
答案 0 :(得分:0)
当您使用ASP.NET并且ddl
是服务器控件时,您需要使用Control.ClientID
。
<%= ddl.ClientID %>
将获取ASP.NET生成的HTML标记的控件ID。
使用
$("#<%= ddl.ClientID %>").change(function() {
//Your code
});
OR
您可以使用ClientIDMode.Static
模式
像
<td>
<asp:DropDownList ID="ddl" ClientIDMode="Static" runat="server">
</asp:DropDownList>
<asp:HiddenField ID="hf" runat="server" />
</td>
然后您只需使用$('#ddl')