在回发时访问控制文本的首选方式
我正在制作一个网站,在整个网站中,我在回发中获取用户输入的方式并不太一致。例如,在一个按钮事件中,该事件获取从文本框中检索的两个字符串,并将它们相加并在标签中输出字符串总和:
protected void btnCalculate_Click(object sender, EventArgs e)
{
string text1 = textBox1.Text; //one way
string text2 = Request["textBox2"]; //the other way
lblSum.Text = text1+text2;
}
我想如果数据已发布到,您会想要使用 Request[""]一个新页面,但对于这种情况,一种方式优于另一种方式,为什么?
I'm making a site and throughout the site I haven't been very consistent with the way I get user input on postbacks. For example, say in a button event that takes two strings retrieved from textboxes and adds them together and outputs the string sum in a label:
protected void btnCalculate_Click(object sender, EventArgs e)
{
string text1 = textBox1.Text; //one way
string text2 = Request["textBox2"]; //the other way
lblSum.Text = text1+text2;
}
I imagine you would want to use Request[""] if the data has been posted to a new page, but for this situation, is one way preferred over another, and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在经典 ASP 3.0 之后,随着 ASP.NET 及其自发布页面的出现,标准方法是 // 单向选项,即 Control.Text , Request[] 是多余的,因为页面回发到自身。
After Classic ASP 3.0 with the advent of ASP.NET and their self posting pages, the standard way is your // One way option, i.e. Control.Text , Request[] is redundant because the page postbacks to itself.
如果回发到同一页面:
要访问另一个页面上的控件,有几种技术,Session、Context、PreviousPage。
如何在 ASP.NET 页面之间传递值
要将字符串添加在一起,使用
或
If the postback is to the same page:
For accessing the control on another page, there are a few techniques, Session, Context, PreviousPage.
How to Pass Values Between ASP.NET Pages
For adding the strings together, use
or
使用
Request[]
有点违背了 Webforms 架构的全部目的。从纯粹的实践层面来看,这也不适用于复杂的表单,因为不能保证服务器上的控件 ID 与客户端上的相同。对于任何不简单包含文本的控件,您将访问非结构化数据,而不是访问其所绑定的控件的更新属性。
无论如何,您确实不应该在 ASP.NET 中从一个页面发布到另一个页面 - 它会破坏体系结构,并且在大多数情况下您没有太多理由想要这样做。
Using
Request[]
kind of defeats the whole purpose of the webforms architecture. At a purely practical level, this will not work for complex forms, either, because the control's ID is not guaranteed to be the same on the server as the client.For any control that's not simply containing text, you will be accessing unstructured data, instead of accessing the updated properties of the control to which it's bound.
You really shouldn't be posting from one page to another in ASP.NET anyway - it breaks the architecture, and there aren't a lot of reasons why you'd want to do that in most situations.