在回发时访问控制文本的首选方式

发布于 2024-10-20 06:17:09 字数 395 浏览 7 评论 0原文

我正在制作一个网站,在整个网站中,我在回发中获取用户输入的方式并不太一致。例如,在一个按钮事件中,该事件获取从文本框中检索的两个字符串,并将它们相加并在标签中输出字符串总和:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鹿港巷口少年归 2024-10-27 06:17:09

在经典 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.

心不设防 2024-10-27 06:17:09

如果回发到同一页面:

textBox1.Text;

要访问另一个页面上的控件,有几种技术,Session、Context、PreviousPage。
如何在 ASP.NET 页面之间传递值

要将字符串添加在一起,使用

String.Concat(text1, text2);

String.Format("{0}{1}",text1, text2);

If the postback is to the same page:

textBox1.Text;

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

String.Concat(text1, text2);

or

String.Format("{0}{1}",text1, text2);
墨落画卷 2024-10-27 06:17:09

使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文