Search code examples
c#htmlasp.netbuttonrunatserver

on button click display a label


I am trying to implement a simple functionality. Basically, it is a search bar. On button click a label should appear with some predefined text+ the search term. Here is my aspx code..

<section class="webdesigntuts-workshop">
    <form id="form1" runat="server">            
        <asp:TextBox type="search" name="search" id="sform" placeholder="What are you looking for?" runat="server" />       
        <asp:label id="searchResultLabel" runat="server" Visible="false" />     
        <button id="lookup" onclick="lookup_Click"  runat="server">Search</button>
    </form>
</section>

Here is my aspx.cs code:

protected void lookup_Click(object sender, EventArgs e)
        {
            String query = sform.Text;
            if (!String.IsNullOrEmpty(query))
            {
                searchResultLabel.Text = "You are looking up the term" + query;
                searchResultLabel.Visible = true;
            }
        }

As of now, on button clock i do not see anything happening. I have added break points but the line of control does not seem to come to .cs code on button click.

Any thoughts?


Solution

  • Using onClick on a regular HTML <button> element will look for a JavaScript event, rather than the code-behind/server-side event you want.

    To reference the server-side event instead, you can do either of the following:

    1. Change your <button> to an <asp:Button> instead.

    <asp:Button id="lookup" onclick="lookup_Click"  runat="server">Search</asp:Button>
    

    (Note: If you're referencing this button by ID anywhere on the front-end, you'll want to add the property ClientIdMode="static" to ensure that the ID is not rewritten when the element is rendered.)

    2. Change onclick="lookup_Click" to onServerClick="lookup_Click".