1

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.

4 Answers 4

10

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"];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.