ASP.NET HTML Server Controls: Accessing and Manipulating HTML Elements from Server-Side Code
Learn how to use HTML server controls in ASP.NET to access and manipulate standard HTML elements from your server-side code. This tutorial explains the `runat="server"` attribute, demonstrates how to interact with HTML elements using their IDs, and shows how to retrieve values from HTML controls in your code-behind file.
ASP.NET HTML Server Controls
Introduction to HTML Server Controls
HTML server controls in ASP.NET are standard HTML elements that have been enhanced to be accessible and manipulated from your server-side code. By default, HTML elements in an ASP.NET Web Forms page are treated as static text and sent directly to the browser. To make an HTML element accessible to your server-side code, you add the `runat="server"` attribute and an id
attribute to the HTML element. Once you do this, you can interact with this HTML element from your code-behind file using its ID. The Request
object can access these controls.
Commonly Used HTML Server Controls
Control Name | Description |
---|---|
<input type="button"> |
Creates an HTML button. |
<input type="reset"> |
Resets form elements to their default values. |
<input type="submit"> |
Submits form data to the server. |
<input type="text"> |
Creates a single-line text input field. |
<textarea> |
Creates a multi-line text input area. |
<input type="file"> |
Allows users to select files for upload. |
<input type="password"> |
Creates a password input field (masked input). |
<input type="checkbox"> |
Creates a checkbox. |
<input type="radio"> |
Creates a radio button. |
<table> |
Creates an HTML table. |
<img> |
Displays an image. |
<select> |
Creates a dropdown list. |
<select size="n"> |
Creates a listbox (multiple selection). |
<hr> |
Creates a horizontal rule. |
Example: Accessing an HTML Server Control
This example shows how to access the value entered into an HTML text box using server-side code.
ASPX Code (htmlcontrolsexample.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="htmlcontrolsexample.aspx.cs" Inherits="asp.netexample.htmlcontrolsexample" %>
<form id="form1" runat="server">
<input type="text" id="Text1" runat="server" />
<input type="submit" id="Button1" runat="server" value="Submit" onclick="Button1_Click"/>
</form>
C# CodeBehind (htmlcontrolsexample.aspx.cs)
using System;
using System.Web.UI;
namespace asp.netexample
{
public partial class htmlcontrolsexample : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string text = Request.Form["Text1"];
Response.Write(text);
}
}
}
Output
(A screenshot showing the output of the entered text after clicking the submit button would be included here.)