asp.net form (translate) multiple forms multiple Form__.net

Source: Internet
Author: User
Tags html form mutex opening and closing tags
asp.net form (translation) multiple forms[2006-06-12 21:46:38 | Author: Admin] Font size: Big | In | Little Dino Esposito
form (form) is an important part of ASP.net development-there is no asp.net web programming model without a form. form is not limited to pure HTML, but there are some limitations in asp.net. For asp.net pages, the form can submit itself, and the ASP.net model provides control state management and postback events. Because ASP.net's single form model makes writing asp.net applications simple and convenient.

Asp. NET, the restrictions on forms may sound weird and arbitrary, but they actually have a direct effect on the ASP.net model. However, there is a reality that is not supported by the ASP.net 1.x form model: There are multiple, non-interference form on the same page. For example, you cannot add a search text box to a page and submit the results to another page.

In the May 2003 issue of MSDN Magazine, I wrote a column about ASP.net 1.x Form programming (see cutting edge:form-based programming in ASP. NET), for the introduction of ASP.net 2.0, there are some changes to the address of the topic submitted to different pages. In this article I will discuss form programming under ASP.net 2.0.

form rendering
Let's explore the ASP.net form world to see how forms, including controls, are actually rendered. The,<form> tag on the asp.net page can be several container controls like <table>, <div>, or a child control of <body>; However, in most pages,<form> is simply a child node of <body>. If a non-container control, such as a textbox, is placed outside the form tag, a run-time error is thrown (this is not checked at compile time). See the following code, excerpt from the AddAttributesToRender method of the TextBox:

protected override void AddAttributesToRender (HtmlTextWriter writer)
{
if (this. Page!= null) this. Page.verifyrenderinginserverform (this);
...
}



The Verifyrenderinginserverform method that calls the page will handle this work. (You should avoid this behavior when you write your own custom server control)

HtmlForm class
HtmlForm inherits from HtmlContainerControl, making the form have the ability to contain child controls. HtmlForm provides programmatic access to the html<form> element on the server side, and its properties list is shown in Figure 1. You can see from the table that the changes in ASP.net 1.x and ASP.net 2.0 are mainly limited to several properties.

A form must have a unique name, and asp.net will be assigned automatically when the name is not specified. The form can be identified by the ID or Name property, and the id attribute takes precedence when set. It is important to note, however, that some programming interfaces use the Name property to be compatible with XHTML. In XHTML, elements is identified by ID instead of name, so it is generally preferable to take the id attribute as the subject.

The form's parent object is a total container control with the Runat property. If such a control does not exist, the page object is used as the parent object. The container for a typical server-side form is <table> or <div> marked as a server-side object.

Figure 2 lists the most commonly used methods in the HtmlForm class. These methods inherit from the System.Web.UI.Control class. Note that the FindControl method searches only the direct child controls of the form. child controls and table-list controls in the inner container will not be found.

Multi-form Management
In general, it is not a great sacrifice to give up support for multiple form systems in the embrace of a single form model. Even though some pages can use multiple forms, they will get a more consistent and natural design-at least for a form that contains a logically related group of input controls, for example, a page will need to support a search form or Login box form, in addition to providing information to the user.

You can merge the search and logon features into the ad hoc class and invoke the same page that displays information, but this is not the best way to construct your code.

If you are porting old code to asp.net, you may find it easier to place the login and search code on another dedicated page. But how can you submit the data on those pages to this page?

In a single form model, the page always submits itself and does not provide a hook for the developer to set the return target. For HTML and ASP programming, the Action property of the form is a single value and is not exposed in the ASP.net HtmlForm class. The single form model is so tightly integrated with the ASP.net platform that you either discard it-or, as an additional option, you can write code in an ASP way without using a server form. As you'll see below, in ASP.net 2.0, you can submit data to another page, but this feature is implemented through the new features of some button controls. Now let's take a look at some of the thorny issues with HTML-not-server-side forms.

In ASP.net, an exception is thrown when more than one HtmlForm control needs to be rendered. After the first HtmlForm control in the page is rendered, a Boolean flag is set to true, indicating whether any htmlform has been rendered and an exception is thrown because the token has been set to True when another htmlform is attempting to render.

If a Web form contains a server form and any number of <form> tags that do not contain the Runat property, no error will result. Without the runat attribute, any markup is rendered directly as a purely single HTML (see Figure 3).

This page contains 2 forms, and the second is an HTML form that does not have the ruan= "server" attribute, and is therefore completely ignored by asp.net. The HTML provided to the browser is legally contained in two <form> elements that point to two different action URLs.

However, functionally this code has a major flaw: the ASP.net programming model cannot be used to retrieve submission data on the Client Form action page. When writing search.aspx, the page's controls cannot read and update their state by using view state and submitting data for the action page of the client form. (The apparent statefulness of ASP.net server controls is obtained from making pages post to themselves) in order to know the data submitted to search.aspx , you must take a traditional style that is directly retrieved from the postback data for the ASP model:

protected void Page_Load (object sender, EventArgs e)
{
Use the Request to retrieve posted data
String texttosearch = request.form["Keyword"]. ToString ();
...
Use standard asp.net to populate the page UI
Keywordbeingused.text = Texttosearch;
}





You can retrieve the returned data using the collection in the HttpRequest Object Protocol specification (page.request equivalent to HttpContext.Current.Request)--use a form for post mode, Use the querystring when using the Get method, or when you want to be compatible with access to form, QueryString, ServerVariables, and cookies. Params The HttpRequest object encapsulates the data before the page is created, so Any event on the page can be invoked at will. For page.request asp.net pages, the request is not required because it can be relied on by a strongly typed programming model, but for the previous, reliable HttpRequest objects are still available for you when needed.

Another interesting thing to note is that when the user clicks the Search button, the search.aspx is invoked, accepting only the data sent back from the HTML form, no view state being returned, and no additional data transfer. If you have to submit your data to another page, using traditional styles is still the smart choice for most efficient performance. As described in the following column, the ASP.net 2.0 cross-page commit feature delivers considerable data fields for Class View state.

Multiple <form> Mark
If multiple server-side form appears on the same Web form, an exception is thrown. What is not easy to find is that, in fact, the Web form can contain any number of server-side form, as long as only one is visible and present at the same time. For example, a page containing 3 <form> with runat= "server" tags is allowed, However, the Visible property of only one form can be set to true. By activating the Visible property of the HtmlForm class, you can change the Active server-side form in the life cycle of the page. This tip doesn't solve the problem of having multiple active form at the same time, but sometimes it helps.

Let's consider the page in Figure 4 where all the <form> is marked as runat= "Server", but only the first is visible, and the mutex form implements a wizard successfully in ASP.net 1.x. By converting the visibility of each form in a button event, you can get the behavior of a class wizard, as shown in Figure 5:



Figure 5 How the Class Wizard page works


This technique is basically useless in asp.net 2.0, because you'll find 2 new controls: MultiView and Wizard. The MultiView control uses a logically equivalent mutex form, but it uses a panel instead of the Orthodox form. MultiView allows you to define multiple mutually exclusive HTML panel and provides an API to toggle the visibility of these panel and ensure that only one is activated and visible at the same time. The MultiView control does not provide a built-in user interface. The Wizard control is just a predefined UI block for MultiView plus a class wizard, which I explained in the MSDN Magazine 2004 11 (see Cutting edge:the asp.net 2.0 Wizard controls).

Cross-page Posting (cross-page submission)
ASP.net 2.0 provides a new built-in build to overwrite the normal processing cycle and allow pages to be submitted to another page. Typically, postback occurs in one of the following two ways: The Submit button is fired or triggered by a script. A typical button submission automatically points to the submission address specified by form, and is more flexible if the submission is through script. In asp.net 2.0, you can configure a control (especially those that implement a new IButtonControl interface) so that it can be submitted to other target pages, and you can refer to the Cross-page posting.

The core controls for implementing IButtonControl are button, ImageButton, and LinkButton. In general, by implementing IButtonControl, all custom controls can have the same effect as buttons in the form. The IButtonControl interface is a typical example of code refactoring in a ASP.net migration from 1.0 to 2.0. The IButtonControl interface aggregates some properties of most button controls (including some HTML button controls) supported by ASP.net 1.x. In addition, new features have been published, such as PostBackUrl and ValidationGroup, and the IButtonControl interface is described in detail in Figure 6. The following code snippet demonstrates how to use:

<form runat= "Server" >
<asp:textbox runat= "Server" id= "Data"/>
<asp:button runat= "Server" id= "Buttonpost" text= "click"
Postbackurl= "Target.aspx"/>
</form>





When the PostBackUrl property is set, the ASP. NET runtime binds a new JavaScript feature to the corresponding HTML element of a button control. The __doPostBack function we use will be replaced with the new Webform_dopostbackwithoptions function, and the client renders the following effect:

<input type= "Submit" Name= "Buttonpost" id= "Buttonpost" value= "click"
onclick= "BLOCKED scriptwebform_dopostbackwithoptions (
New Webform_postbackoptions ("Buttonpost", "" ",
False, "", "target.aspx", False, False)) "/>





The result is that when the user clicks on the button, the current form submits the content to the specified target page. So what about the view state? When you have a control that can cross-page posting, the page creates a hidden field named __previouspage that contains information about the submission page. The target page uses this information to create a full state reference to invoke the Page object.

On the target page, you can use a new property previouspage of the page class to refer to the Submit page and all the controls on the page. The following is the background code that the target page retrieves for a TextBox content in form:

protected void Page_Load (object sender, EventArgs e)
{
Retrieves some posted data
TextBox txt = (textbox) Previouspage.findcontrol ("TextBox1");
...
}





By using the PreviousPage property of the page class, you can access any input control declared on the Submit page. Access to the input control is weakly typed and the FindControl method is used indirectly. The problem before the fact is that the target page does not know any information about the type of submission page. Similarly, It also does not provide access to the specified members of the source page class.

Also, note that FindControl only finds controls in the current container, if the control you are looking for is inside another control (such as a template), You must first take this container reference and then search the container to find the control. Another way is needed to avoid full recourse to FindControl.

To retrieve the values on the submission page, FindControl will only provide a secure option when you do not know in advance which target page will be invoked. However, when using cross-page posting in the context of an application, There will be an opportunity to know exactly who will call and how to call this page. In this case, you can use the PreviousPageType directive to make the target page's PreviousPageType property strongly typed as the source page class. On the target page, add the following directive:

Directive can be one of two mutually exclusive attributes: VirtualPath or typename.virtualpath refers to the URL of the submitted page. TypeName indicates the type of the calling page. The previouspagetype directive causes the target page PreviousPage property to return an object reference to the same type of page on the given path (or the type specified by the TypeName property). The fact is that you cannot access the input control directly. In asp.net, each page class contains the corresponding protected member of the child control. Unfortunately, you cannot invoke protected members of an external class. In fact, only derived classes can access protected members of the parent class.

To do this, you must access the Submit page information on the call page in a public property. For example, the Illusion crosspostpage.aspx page contains a textbox with the name _textbox1, so that it can be accessed on the target page, You must add the following code in the background class:

Public TextBox TextBox1
{
get {return _textbox1;}
}



Calling the potential target as Cross-page does not automatically make the target page a different type. Usually the target page is always called by itself, such as through a hyperlink. When this happens, the PreviousPage property returns null and other postback-related attributes (like IsPostBack ). For dual-function pages, a good idea is to add additional code to distinguish the behavior of the page. The code in the following Page_Load event causes the page to work only in the Cross-page invocation mode:

if (previouspage = null)
{
Response.Write ("Sorry, that's not the right way to invoke me.");
Response.End ();
Return
}



Page redirection
In addition to the PostBackUrl property of the button control, ASP. NET provides a mechanism for passing controls and values between another page: the Server.Transfer method. When you call this method, the URL of the new page is not reflected in the browser's address bar, Because this page shifts to the server side-no indirect events occur on the client. The following code demonstrates how to use this method for page orientation:

protected void Button1_Click (object sender, EventArgs e)
{
Server.Transfer ("targetpage.aspx");
}





Note that the calling code that is redirected to the page is not executed. Finally, transfer is just a way of paging. However, it is very effective in two situations: first, the client's request. For example, use Response.Redirect. A request in the same application is reused in a new page request.

For ASP.net 1.x, you can get the calling object by using the Handler property of the HTTP context, as shown here:

Page caller = (page) Context.Handler;

Because the handler property returns a valid object reference, the principal page can access its public members, but as we discussed above, the controls that do not directly access the protected level on the page.

This programming model is also used for ASP.net 2.0, but in asp.net 2.0 it becomes simpler and no longer requires the use of handler. You can use with Cross-page Postings the same programming model and uses a non-empty previouspage attribute and a strongly typed @previouspagetype instruction to access the input domain. So how can the page detect it being Transfer call or Cross-page postback? The PreviousPage are non-null in both ways, but the previouspage of the Page.iscrosspagepostback object is Cross-page The posting method is true, and erver transfer is false.

Summary
From one page to another there are many ways to achieve--cross-page posting,server transfer,html forms, cookies, session-state, query strings, or other methods, and so on. What is the most effective? In asp.net 2.0, cross-page posting and server transfer provide a common programming model, but potentially move large chunks of data through view state. and whether the information really needs to depend on the description of the target page. In many cases, the target page simply needs to receive some of the parameters for the startup operation. The If is so,html client forms can be more efficient with mobile data, although HTML forms require a programming model for the class ASP.

ASP.net 2.0 adds some new features to the HtmlForm class, but the core behavior does not change, so submitting itself is still the main method of ASP.net programming. You can mix the client form and the server form, or you can have multiple server form, but only one is visible at the same time.

Questions and comments please send to cutting@microsoft.com.


Introduction of the author
Dino Esposito in Rome, Italy, serving as lecturer and advisor. The author of "Programming ASP.net" and the new book "Introducing ASP.net 2.0" (both books are published by Microsoft Press) He spends most of his time teaching asp.net and ado.net courses and speaking at various conferences.
If you want to get in touch with Dino, please send email to cutting@microsoft.com or browse his blog site: Http://weblogs.ASP.NET/despos.


--------------------------------------------------------------------------------

From MSDN Magazine September 2005 issue.

--------------------------------------------------------------------------------
Figure 1 Properties of the HtmlForm Class

Property asp.net 1.x asp.net 2.0 Description
Attributes inherited from Control. Gets a Name/value collection with the "attributes declared on the" tag.
ClientID inherited from Control. Gets the value of UniqueID.
Controls inherited from Control. Gets A Collection object that represents the child controls of the form.
DefaultButton String property. Gets or sets the button control to display as the default button on the form.
DefaultFocus String property. Gets or sets the button control into give input focus when the form is displayed.
Disabled Gets or sets a value indicating whether the form is Disabled. Matches the disabled HTML attribute.
Enctype Gets or sets the encoding type. Matches the enctype HTML attribute.
ID inherited from Control. Gets or sets the programmatic identifier of the form.
InnerHtml inherited from HtmlContainerControl. Gets or sets the markup content found between the opening and closing tags of the form.
InnerText inherited from HtmlContainerControl. Gets or sets the text between the opening and closing tags of the form.
Method Gets or sets a value this indicates how a browser posts form data to the server. The default value is POST. Can is set to get if needed.
Name Gets the value of UniqueID.
Style Gets A collection of all cascading style sheet (CSS) properties applied to the form.
Submitdisabledcontrols indicates whether to force controls in the client to submit disabled values, their allowing to Preserve their values after the page posts the server. False by default.
TagName Returns "Form".
Target Gets or sets the name of the frame or window to render the HTML generated for the page.
UniqueID inherited from Control. Gets the unique, fully qualified name of the form.
Visible Gets or sets a value that indicates whether the form is rendered. If false, the form isn't rendered to HTML.

--------------------------------------------------------------------------------
Figure 2 Methods of the HtmlForm Class

Method asp.net 1.x asp.net 2.0 Description
Applystylesheetskin applies the skin in the defined page theme in the manner defined by StyleSheetTheme.
DataBind Calls The DataBind method on all child controls.
FindControl retrieves and returns that matches the specified ID.
Focus Sets The input focus to a control.
Hascontrols Indicates whether the form contains any child controls.
RenderControl outputs the HTML code for the form. IF tracing is enabled, caches tracing information to being rendered later, at the end of the page.

--------------------------------------------------------------------------------
Figure 3 Server and Client Forms in the Same Page
<body>
<table><tr><td>
<form id= "Form1" runat= "Server" >
</form>
</td>
<td>
<form method= "POST" action= "search.aspx" >
<table><tr>
<td>Keyword</td>
<td><input type= "text" id= "Keyword" name= "Keyword"/></td>
</tr><tr>
<td><input type= "Submit" id= "Go" value= "Search"/></td>
</tr></table>
</form>
</td>
</tr></table>
</body>



--------------------------------------------------------------------------------
Figure 4 Markup for a asp.net 1.x wizard-like Page
<body>
<form id= "step0" runat= "Server" visible= "true" >
<asp:textbox runat= "Server" id= "Textbox1"/>
<asp:button id= "Button1" runat= "Server" text= "Step #1"
onclick= "Button1_Click"/>
</form>
<form id= "Step1" runat= "Server" visible= "false" >
<asp:textbox runat= "Server" id= "Textbox2"/>
<asp:button id= "Button2" runat= "Server" text= "Previous Step"
onclick= "Button2_Click"/>
<asp:button id= "Button3" runat= "Server" text= "Step #2"
onclick= "Button3_Click"/>
</form>
<form id= "Step2" runat= "Server" visible= "false" >
<asp:button id= "Button4" runat= "Server" text= "Finish"
onclick= "Button4_Click"/>
</form>
</body>



--------------------------------------------------------------------------------
Fig. 6 IButtonControl Interface

Property Description
CausesValidation Boolean value indicating whether validation is performed then the control is clicked.
CommandArgument Gets or sets a optional parameter passed to the button ' s Command event along with the associated CommandN Ame.
CommandName Gets or sets the command name associated with the button this is passed to the command event.
PostBackUrl indicates the URL that would handle the postback triggered through the button control.
Text Gets or sets the caption of the button.
ValidationGroup Gets or sets the name of the validation group to which the button belongs.
Visible Boolean value indicating whether the button control is rendered.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.