jQuery AJAX 源代码是同一页面上的一个 ASP.NET 函数(Default.cshtml).如何发送/接收

本文关键字:NET ASP 一个 函数 cshtml 接收 何发送 Default 源代码 AJAX 一页 | 更新日期: 2023-09-27 18:32:05

我们正在从PHP迁移到 ASP.NET,我对jQuery有点陌生。所以,我对这个函数有点问题:

[System.Web.Services.WebMethod]
internal static string[] GetSearchSuggestions(string SearchQuery)
{
    string ConnectionString = "Data Source=<omitted>;Initial Catalog=<omitted>;Integrated Security=True";
    string TSQL_Query = String.Format("SELECT DISTINCT TOP 5 [colum-name] from [table] WHERE [column-name] LIKE '{0}%' AND len([column-name]) > 0", SearchQuery);
    List<string> SearchSuggestions = new List<string>();
    using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionString))
    {
        using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(TSQL_Query, connection))
        {
            connection.Open();
            System.Data.SqlClient.SqlDataReader r = command.ExecuteReader();
            while (r.Read())
            {
                SearchSuggestions.Add(r.GetString(0));
            }
        }
    }
    return SearchSuggestions.ToArray();
}

这是我的jquery:

    <script type="text/javascript">
        $(document).ready(function () {
        $("#SearchQueryBox").autocomplete({
            source: function (request, response) 
            {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: GetSearchSuggestions,
                    data: "{'term':'" + $("#SearchQueryBox").val() + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("error");
                    }
                });
             }
          });
       });
    </script>

现在,如果我把它变成一篇加载下一页的简单帖子,上面的 ASP.NET C# 代码就可以了。但是,在我的任何测试情况下,我似乎都无法获得jQuery响应。

此页面称为 Default.cshtml,使用的是 ASP.NET Razor 语法。该函数位于同一页面上,如下所示:

@functions
{
    // GetSearchSuggestions() code here
}

如何适当地发布到同一页面上的 ASP.NET 功能,并收到响应?

提前感谢!

jQuery AJAX 源代码是同一页面上的一个 ASP.NET 函数(Default.cshtml).如何发送/接收

我假设你使用的是 ASP.NET MVC。如果是这种情况:

您需要将函数(即在 Default.cshtml 中)移动到控制器中具有HttpPost的新 ActionMethod。

因此,假设您的 Default.cshtml 由 HomeController.cs 加载。在 HomeController.cs 中,您将创建新的操作方法:

[HttpPost]
public void ActionResult GetSearchSuggestions() {
    // GetSearchSuggestions() code here
}

此外,在您的jQuery中,.ajax的选项url将需要是您网站的URL。同样,使用我上面给出的示例,URL将被 http://www.example.com/Home/GetSearchSuggestions你不能像这样从 jQuery 调用 C# 或 ASP.NET 函数,你必须指定该 ActionMethod 的 URL。

更新

第二眼,我不确定你的internal static string[] GetSearchSuggestions(string SearchQuery)是否在哪里。但是你可以把它移到HomeController,.cs我说的。只需删除[System.Web.Services.WebMethod]并更改为[HttpPost]