quinta-feira, janeiro 19, 2006

Dynamic Web Controls, Postbacks, and View State

Dynamic Web Controls, Postbacks, and View State
By Scott Mitchell

Introduction
As I've written about in two previous articles here on 4Guys - Dynamic Controls in ASP.NET and Working with Dynamically Created Controls - ASP.NET makes it easy to programmatically add Web controls. Armed with this capability, you can offer a truly customized experience for your users. For example, your site might load particular navigational elements as user controls, based upon the logged on user's preferences. Or when collecting information from your users, you might display different input fields prompting for different data based on the user's age, location, gender, and so on.

One of the main challenges with working with dynamically added controls is that these controls must be programmatically added on each postback. That is, you can't just load these controls on the first page load, and then not reload them on subsequent postbacks. Failure to explicitly add the controls on each postback will cause the controls to literally disappear on postbacks. To further complicate things, the point in the page's lifecycle when dynamic controls are added is important if you want to maintain changed values across postback. For example, imagine you had a Web page that displayed a series of input form fields based on the user visiting the page. The idea here would be to allow the visitor enter some values into these custom input form fields, and then submit the form, having the data saved. If the dynamic Web controls are not added at the correct time in the page's lifecycle, the values entered by the visitor will be lost on postback.

In this article we will examine how to add dynamic Web controls to a page in such a manner that you will not need to worry about losing form field values on postback. Specifically, we'll look at how to create a page whose form fields are dependent upon the user visiting the page, and how this user can enter their data into these form fields and have it saved on form submission. Since this article builds upon concepts discussed earlier, please make sure you have read both Dynamic Controls in ASP.NET and Working with Dynamically Created Controls before tackling this article.

Article: 4 Guys From Rolla

Sem comentários: