开发者

How to programmatically distinguish element/control types from ASP.NET Request.Form key/value collection?

开发者 https://www.devze.com 2022-12-14 07:26 出处:网络
I have a simple ASP.NET web form as below: <form id=\"form1\" runat=\"server\"> <asp:TextBox ID=\"txt\" runat=\"server\"></asp:TextBox>

I have a simple ASP.NET web form as below:

<form id="form1" runat="server">
    <asp:TextBox ID="txt" runat="server"></asp:TextBox>
    <asp:DropDownList ID="ddl" runat="server">
        <asp:ListItem Text="X" Value="X"></asp:ListItem>
        <asp:ListItem Text="Y" Value="Y"></asp:ListItem>
        <asp:ListItem Text="Z" Value="Z"></asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="btn" runat="server" Text="Button" />
</form>
开发者_开发知识库

Request.Form contains the following key/value pairs:

[0] _VIEWSTATE
[1] _EVENTVALIDATION
[2] txt
[3] ddl
[4] btn

How do I differentiate the button (btn) from Textbox value (txt) or DropDown List value (ddl)? Or do I need to somehow come up with a naming convention? I am trying to iterate Request.Form object and save form values into a hashtable for later use.

Thanks.


The way to differentiate between the various Request.Form fields is to associate the field names with the control names--which is exactly what each control does.

Each control knows its own ID. During the Initialization phase, each control sets or restores its state based on both Request.Form and ViewState.

For dynamically created controls, the Framework will handle this for you, provided that you create the controls and add them to the control tree before the Init phase (such as in the OnPreInit event handler).

If you want to do it yourself, you can mimic the process by walking the control tree.


You can't. To the server it's a simple name:value collection.

Why not let the framework take care of this for you?

In the codebehind you can retrieve the values via their properties:

ddl.SelectedText
txt.Text
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号