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!

2
  • 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 stackoverflow.com/questions/10688951/… Commented Dec 1, 2014 at 18:58
  • Yes, here you go: pastebin.com/gwcAYUYP Commented Dec 1, 2014 at 19:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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: pastebin.com/gwcAYUYP - am I doing anything wrong there? Thanks!
@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.
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: <asp:TextBox ID="tb_SearchQuery" runat="server" AutoPostBack="true"></asp:TextBox> <asp:Button ID="btn_Search" runat="server" OnClick="btn_Search_Click" Text="Search" />
$(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); } }); } }); });
I'm glad this gave you a push in the right direction ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.