Ian
Ian

Reputation: 105

Why am I unable to reference html controls from code behind while using runat="server"?

HTML:

<tr>
    <td>
        <button type="button" id="serverbtn" name="serverbtn" runat="server" 
        OnClick="serverbtn_Click">Submit
        </button>
    </td>
    <td colspan="2">
        <input id="servertxt" name="servertxt" runat="server" />
    </td>
</tr>

Code behind:

namespace WebApp
{ 
    public class ServerSide
    {        
        public void serverbtn_Click(object sender, EventArgs e)
        {
            String txt = servertxt.Value;
        }
    }
}

I'm new to asp.net and to building websites in general. I want to pass the text entered into an html input to the C# code behind for processing. From what I've read, adding the runat="server" allows these controls to be visible to the C#. However, the servertxt control says that it doesn't exist in the current context. This project uses the empty website in Visual Studio and not a webform/webapp. I added the html and C# file to the project manually. What am I missing here?

Upvotes: 1

Views: 869

Answers (1)

Alexander
Alexander

Reputation: 4527

The <input> is an HTML tag that is used for a form's data storage on client-side. But it isn't a server control. Moreover, there is no runat attribute for <input> element in HTML Specification. You should use <asp:TextBox> server-side control instead. Also, if you want to handle button click event on the server-side then you have to use <asp:Button> control instead of <button> element.

Upvotes: 1

Related Questions