0

I'm a bit of a newbie to ASP.NET, but I'm pretty decent at C#. I find this approach very easy in PHP, but it's a lot different in ASP.NET.

My problem is that I don't know how to query ASP.NET functions from jQuery. I have an ASP.NET WebForms project, and the code-behind (TestMe.aspx.cs) contains the following code:

    [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;
    }

And I have this function in the same file (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>");
        }
    }

Now, this DOES produce results, but only after clicking the textbox button. I want to make this appear automatically as the user types.

How do I do that?

Thanks!

  • 1
    can you show your Markup in the .aspx page.. how come you can't just call the method `OnClick` from their..? here is an example on how to call methods with [WebMethod] attribute inside of a .cs file for example there are many ways to do this as well http://stackoverflow.com/questions/10688951/calling-webmethod-ina-aspx-cs-file-using-jquery-ajax – MethodMan Dec 01 '14 at 18:58
  • Yes, here you go: http://pastebin.com/gwcAYUYP –  Dec 01 '14 at 19:17

1 Answers1

2

Make the method public and static (leave the WebMethod attribute on it):

[WebMethod]
public static List<string> GetSearchSuggestions(string SearchQuery)
{
   ....
}

From 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);
    }
});

Update:

Per your comments, if all the textbox is used for is this AJAX function, I suggest making it a simple HTML control:

<input type="text" id="tb_SearchQuery" />

And here is the javascript you posted in the comments:

$(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);
                }
            });
        }
    });
});

This works on my system. If you are not getting results, you can try troubleshooting:

  1. Inspect the javascript console for errors.

  2. Step through the javascript in a debugger (Firebug, or developer tools in Chrome, etc) to see if $("#tb_SearchQuery").val() actually gets you anything.

  3. Put a breakpoint in TestMe.aspx.cs in GetSearchSuggestions() to see if a) it's being called, and b) SearchQuery is populated as expected.

Slippery Pete
  • 3,051
  • 1
  • 13
  • 15
  • Hi, I'm trying your suggested changes, and that does not work at all. I've updated **SearchQuery: "foo"** to **SearchQuery: $("#tb_SearchQuery").val()**, and that doesn't work either. Here's my full code: http://pastebin.com/gwcAYUYP - am I doing anything wrong there? Thanks! –  Dec 01 '14 at 19:14
  • 2
    @heh pastebin is blocked here at work, but regardless you should post any relevant code here on SO so others may benefit in the future. Please describe "doesn't work" - error? No results? Note that ASP may mangle the ID of the web control, so make sure `$("#tb_SearchQuery")` is correct. – Slippery Pete Dec 01 '14 at 19:18
  • Hi, the code is too long for me to post here. It doesn't work as in, there are no results at all. No errors, just no results. How does ASP.NET mangle the ID? I changed it to tb_SearchQuery. For example: ** ** –  Dec 01 '14 at 19:21
  • $(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); } }); } }); }); –  Dec 01 '14 at 19:24
  • Thank you for your update. However, using the asp.net controls is required by this project. –  Dec 01 '14 at 20:02
  • So I decided to just switch to using standard input boxes, and now it works. I get the data back, but doesn't display. When I try to append the results to a div tag, it doesn't display. I'll figure it out, though! Thank you. –  Dec 01 '14 at 21:39
  • 1
    I'm glad this gave you a push in the right direction ;) – Slippery Pete Dec 01 '14 at 21:40