如何以编程方式区分 ASP.NET Request.Form 键/值集合中的元素/控件类型?
我有一个简单的 ASP.NET Web 表单,如下所示:
<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 包含以下键/值对:
[0] _VIEWSTATE
[1] _EVENTVALIDATION
[2] txt
[3] ddl
[4] btn
如何区分按钮 (btn) 与文本框值 (txt) 或下拉列表值 ( ddl)?或者我是否需要以某种方式提出命名约定?我正在尝试迭代 Request.Form 对象并将表单值保存到哈希表中以供以后使用。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
区分各个 Request.Form 字段的方法是将字段名称与控件名称相关联——这正是每个控件的作用。
每个控件都知道自己的 ID。在初始化阶段,每个控件根据Request.Form 和ViewState 设置或恢复其状态。
对于动态创建的控件,框架将为您处理此问题,前提是您在 Init 阶段之前创建控件并将它们添加到控件树中(例如在 OnPreInit 事件处理程序中)。
如果您想自己动手,可以通过遍历控制树来模拟该过程。
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: