【发布时间】:2019-05-15 11:50:23
【问题描述】:
我无法使用Jquery Ajax 从Master Page 呼叫[WebMethod]。
我收到如下错误:
GetCompletionList(禁止)
我在 Default.aspx 网页的markup 上的Jquery 中有以下代码,其中包含母版页:
<script type="text/javascript">
function ShowImage() {
document.getElementById('txSearch')
.style.backgroundImage = 'url(/aspnet/img/snake_transparent.gif)';
document.getElementById('txSearch')
.style.backgroundRepeat = 'no-repeat';
document.getElementById('txSearch')
.style.backgroundPosition = 'right';
}
function HideImage() {
document.getElementById('txSearch')
.style.backgroundImage = 'none';
}
$(function () {
$("[id$=txSearch]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("Mymasterpage.master/GetCompletionList") %>',
data: "{ 'prefixText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.toString,
val: item.toString
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfSearch]").val(i.item.val);
},
minLength: 1
});
});
</script>
在 Master Page Mymasterpage.master.cs 的 Code Behind 中我有这个:
[ScriptMethod()]
[WebMethod]
public static List<string> GetCompletionList(string prefixText)
{
using (OdbcConnection con =
new OdbcConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString))
{
using (OdbcCommand com =
new OdbcCommand())
{
com.CommandText = " SELECT ";
com.CommandText += " sName ";
com.CommandText += " FROM ";
com.CommandText += " `tbl_name` ";
com.CommandText += " WHERE ";
com.CommandText += " sName LIKE CONCAT('%',?,'%'); ";
com.Parameters.AddWithValue("param1", prefixText);
com.Connection = con;
con.Open();
List<string> countryNames = new List<string>();
using (OdbcDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
countryNames.Add(sdr["sName"].ToString());
}
}
con.Close();
return countryNames;
}
}
}
为什么会这样?
如何解决?
谢谢
【问题讨论】:
-
请参阅此answer。简而言之,您不能在 MasterPage 中使用 Web 方法,而应该将它们放在 WebService 或 WCF 服务中。
标签: c# jquery ajax methods master-pages