ra170
ra170

Reputation: 3683

How to access data from html controls in asp.net

How do I access data from html in asp.net in the .cs (code behind) file?

In .aspx page I have:

             <tr>
                <td>Username:</td><td><input id="username" type="text" /></td>
             </tr>
             <tr>
                <td>Password:</td><td><input id="password" type="password" /></td>
             </tr>
             <tr>

I know I can convert this to something like:

    <tr>
        <td>Username:</td><td><asp:TextBox ID="username" TextMode="SingleLine" runat="server"></asp:TextBox></td>
     </tr>
     <tr>
        <td>Password:</td><td><asp:TextBox ID="password" TextMode="Password" runat=server></asp:TextBox></td>
     </tr>

This will allow me to access the controls via IDs. However I was wondering if there was a way of accessing data without using asp.net server-side controls.

Upvotes: 1

Views: 7972

Answers (4)

Surya sasidhar
Surya sasidhar

Reputation: 30293

This is your code:

<tr>
    <td>Username:</td>
    <td><input id="username" type="text" /></td>
</tr>
<tr>
    <td>Password:</td>
    <td><input id="password" type="password" /></td>
</tr>

You can just add the runat="server" attribute to the Html controls:

<tr>
    <td>Username:</td>
    <td><input id="username" runat="server" type="text" />  <!--NOTE THE RUNAT="SERVER"--></td>
</tr>
<tr>
    <td>Password:</td>
    <td><input id="password" **runat="server"** type="password" /></td>
</tr>

Now you can access the controls in asp.net.

Upvotes: 0

Stuart
Stuart

Reputation: 12215

ASP.NET controls, are in essence HTML controls wrapped, so an asp:Button will render as a input Html control. Some web developers prefer using Html controls due to the smaller size. Therefore each HTML control will map to a asp server control. As the previous answer, from Joel, add the runat="server", then the control can be referenced by the ID from the code behind.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

Add runat="server" to the controls, and then you can access them from the code-behind almost as if they were <asp:______ /> controls.

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532445

Give the inputs a name as well as an id and you will be able to get the values from Request.Form. Inputs without names are not sent back with the form post.

<input id="username" name="username" type="text" />
<input id="password" name="password" type="password" />


var username = Request.Form["username"];
var password = Request.Form["password"];

Upvotes: 10

Related Questions