[英]How do I use Webforms and ASP.NET MVC together in an ASP.NET Webforms Website project?
[英]How do I trigger a function in ASP.NET from jQuery? WebForms
我是ASP.NET的新手,但是在C#方面我相當不錯。 我發現這種方法在PHP中非常容易,但是在ASP.NET中卻大不相同。
我的問題是我不知道如何從jQuery查詢ASP.NET函數。 我有一個ASP.NET WebForms項目,其背后的代碼( TestMe.aspx.cs )包含以下代碼:
[WebMethod]
internal List<string> GetSearchSuggestions(string SearchQuery)
{
string ConnectionString = "Data Source=<omitted>;Initial Catalog=<omitted>;Integrated Security=True";
string TSQL_Query = "<omitted>";
List<string> SearchSuggestions = new List<string>();
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(TSQL_Query, connection))
{
connection.Open();
System.Data.SqlClient.SqlDataReader r = command.ExecuteReader();
while (r.Read())
{
SearchSuggestions.Add(r.GetString(0));
}
}
return SearchSuggestions;
}
我在同一文件( TestMe.aspx.cs )中具有此功能:
protected void tb_SearchQuery_TextChanged(object sender, EventArgs e)
{
string Input = SanitizeInput(this.tb_SearchQuery.Text);
if (!String.IsNullOrEmpty(Input) && Input.Length > 1)
{
Response.Write("<ul>");
foreach (string item in GetSearchSuggestions(Input))
{
Response.Write("<li>" + item + "</li>");
}
Response.Write("</ul>");
}
}
現在,這確實產生了結果,但是僅在單擊文本框按鈕之后才產生結果。 我想使它在用戶鍵入時自動出現。
我怎么做?
謝謝!
將方法設為公共和靜態(在其上保留WebMethod
屬性):
[WebMethod]
public static List<string> GetSearchSuggestions(string SearchQuery)
{
....
}
從javascript:
$.ajax({
url: "TestMe.aspx/GetSearchSuggestions",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ SearchQuery: "foo" }),
dataType: "json",
success: function (r) {
console.log(r);
}
});
更新:
根據您的評論,如果所有文本框都用於此AJAX函數,則建議使其成為一個簡單的HTML控件:
<input type="text" id="tb_SearchQuery" />
這是您在評論中發布的javascript:
$(document).ready(function () {
$("#tb_SearchQuery").autocomplete({
source: function (request, response) {
$.ajax({
url: "TestMe.aspx/GetSearchSuggestions",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ SearchQuery: $("#tb_SearchQuery").val() }),
dataType: "json",
success: function (r) {
console.log(r);
}
});
}
});
});
這適用於我的系統。 如果未獲得結果,則可以嘗試進行故障排除:
檢查javascript控制台是否有錯誤。
逐步調試器中的JavaScript(Firebug,或Chrome中的開發人員工具,等等),看看$("#tb_SearchQuery").val()
確實為您$("#tb_SearchQuery").val()
。
在GetSearchSuggestions()
TestMe.aspx.cs中放置一個斷點,以查看a)是否正在調用它,b)是否按預期填充SearchQuery
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.