我正在关注如何从 javascript 调用 c# 函数的示例。我有一个应该自动完成用户输入的文本框。这在我将目标控制为文本框时起作用,这意味着当用户键入时,文本框将自动完成请求。
但是,我想要一个列表框来保存匹配的案例。
这是javascript代码:
function CallMe(src, dest) {
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetNews(ctrl.value, CallSuccess, CallFailed, dest);
}
function CallSuccess(res, destCtrl) {
var dest = document.getElementById(destCtrl);
dest.value = res;
}
function CallFailed(res, destCtrl) {
alert(res.get_message());
}
下面是 C# 代码,它接受一个字符串输入并返回与输入匹配的条目。 我已经通过使用遍历列表并将项目添加到列表框的 foreach 循环对此进行了测试,我需要以 ajax 方式/样式执行此操作。
不过我希望使用 javascript 不断更新它。
[System.Web.Services.WebMethod]
public static List<string> GetNews(string input)
{
List<string> listan = new List<string>();
SqlDataReader reader;
string tempstr = "";
if (input == null || input.Length == 0)
return null;
SqlConnection conn = null;
try
{
string connection = "example";
conn = new SqlConnection(connection);
string sql2 = "Select News from Nyheter where News LIKE '%'+@News+'%'";
SqlCommand cmd = new SqlCommand(sql2, conn);
cmd.Parameters.AddWithValue("News", input);
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
tempstr = (string)reader["News"];
listan.Add(tempstr);
}
return listan;
}
catch (SqlException ex)
{
return null;
}
finally
{
conn.Close();
}
}
这是加载代码,第一个示例有效,Textie 是一个在找到匹配项时自动完成的文本框。问题是我希望将匹配项添加到列表框中。第二个例子不起作用,我不知道为什么,项目没有被添加到列表框中。
if (!Page.IsPostBack)
{
Textie.Attributes.Add("onblur", "javascript:CallMe('" + Textie.ClientID + "', '" + Textie.ClientID + "')");
//ListBox1.Attributes.Add("onblur", "javascript:CallMe('" + Textie.ClientID + "', '" + ListBox1.ClientID + "')");
}
提示将不胜感激,有没有更简单的方法来解决这个问题?
最佳答案
Textie.Attributes.Add("onblur", "javascript:CallMe('" + Textie.ClientID + "', '" + Textie.ClientID + "')");
将此代码放在页面加载中,但不要放在“NOt postback”代码中。
关于c# - 以ajax方式将项目添加到列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13877710/