开发者

Preferred way to access control text on postback

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["textBo开发者_如何学JAVAx2"];    //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?


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.


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);


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜