Manipulating data in asp.net 2.0: Creating Master Pages and site navigation _ self-study Process

Source: Internet
Author: User
Tags eval html tags

Introduction

Usually, the user-friendly personalized site has a consistent, Site Unified page layout and navigation system. The two new features introduced in ASP.net 2.0 provide a simple and effective tool for page layout and site navigation on the consolidated site, which are master page and site navigation. The master page allows developers to create a unified site template and a specified editable region. This way, the ASPX page only needs to provide a fill for the editable region specified in the template page, and all other tags defined in the master page will appear in all ASPX pages that use that master page. This model allows developers to manage and define the page layout of a site in a unified way, so it is easy to get a unified vision and feel of the page and also easy to update.

The site navigation system allows developers to define site maps and provide APIs for querying site map information through programs. The new navigation controls include Menu,treeview and SiteMapPath, which makes it easy to render all or part of the site map in a generic navigation user interface element. We will use the default site navigation provider, which means our sitemap will be defined in an XML-formatted file.

To illustrate these concepts and make our tutorial sample site usability better, let's define a site-by-page layout, implement a sitemap, and add a navigation UI through this course. At the end of this course our sample site has a beautiful design effect.

Figure 1: The final results of this course

Step 1: Create the motherboard page

The first step is to create a motherboard page for our site. So far our site has only one typed dataset (Northwind.xsd, located in the App_Code folder), Business Logic Layer Class library (Productsbll.cs,categoriesbll.cs, etc., which are all in App_ Code folder), the database (Northwind.mdf, located in the App_Data folder), the configuration file (Web.config), and a CSS file (style.css).
I've collated these pages and files to illustrate that the data access layer and business logic layer described in the previous two lessons will reuse these examples in more detail in future courses.

Figure 2: The files in our project

To create a motherboard page, right-click the project name in Solution Manager and select Add New item. Then select the motherboard type from the Template List window and name it Site.master

Figure 3: Adding a motherboard page to the site

Define the site's unified page layout in the master page. You can use Design view to define the layout or controls you need, and you can also manually add tags to the Code view. A cascading style sheet defined in the external file style.css is used in our master page to define the location and style. Maybe you don't know how the following tags show, the style sheet rule defines that the contents of the <div> labels for navigation are absolutely positioned to the left of the page and are fixed to 200 pixels wide.

Site.master

<%@ Master language= "C #" autoeventwireup= "true" codefile= "Site.master.cs" inherits= "Site"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

A master page defines a fixed layout and editable regions that can be filled with ASPX pages that use the motherboard page
This editable region is displayed through the ContentPlaceHolder control and is located in the <div> tag. There is only one ContentPlaceHolder (maincontent) in our motherboard page, but the motherboard page can contain multiple ContentPlaceHolder controls.

Enter the above tag and switch to Design view to see the layout of the master page. All ASPX pages that use this master page have such a unified layout, and the MainContent area is where the ASPX page is left to show its talent.

Figure 4: The master page displayed in Design view

Step 2: Add a home page to the site

After defining the master page, we are ready to add some ASPX pages to the site. Let's start by adding our homepage degault.aspx. Right-click the project name in Solution Manager and choose Add New Project. Select the Web Form option from the list of templates and name it default.aspx. Also, tick the check box for select a motherboard page.

Figure 5: Add a new Web form and tick the Select master page check box

When you click on the OK button, you will be asked which motherboard page your new ASPX page uses. Maybe you have multiple motherboard pages in your project, but we only have one.

Figure 6: Select the motherboard page you want to use

When you select a master page, the new ASPX contains the following tags:

Default.aspx

<%@ Page language= "C #" masterpagefile= "~/site.master" autoeventwireup= "true"
 codefile= "Default.aspx.cs" inherits= "_default" title= "Untitled Page%> <asp:content id=" Content1 "contentplaceholderid=" MainContent
"
 runat=" Server >
</asp:Content>

There is a reference to the master page (masterpagefile= "~/site.master") in the @page directive, and the markup for the ASPX page includes a content control corresponding to the ContentPlaceHolder control defined in the master page. The ContentPlaceHolderID property of this content control is mapped to the specified ContentPlaceHolder control. You can place tags in the content control that you want to display in the position of the corresponding ContentPlaceHolder control.

Set the title property of the @page directive to home and add some welcome words to the content control:

Default.aspx

<%@ Page language= "C #" masterpagefile= "~/site.master" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits=
 "_default" title= "Home"%> <asp:content id= "Content1" contentplaceholderid= "maincontent" runat= "Server" >  

The title attribute in the @Page directive allows us to define the title in the ASPX page, even though the <title> element is already defined in the master page. We can also set the title of the page using the Page.title programming method. Note that the stylesheet referenced in the master page (such as STYLE.CSS) is automatically corrected to apply to each ASPX page, regardless of the relationship between the directory of the ASPX page and the parent Board page catalog.

Switch to Design view we'll see how our page will look in the browser. Note: In Design view, the contents of an ASPX page can be modified only by editable regions, and the ContentPlaceHolder portion of the markup defined on the master page is grayed out.

Figure 7: Editable and non editable regions displayed in Design view

When the Default.aspx page is accessed by the browser, the ASP.net engine merges the contents of the master page and the contents of the ASPX page, and renders the merged content as the final HTML sent to the browser. When the contents of the master page are updated, all ASPX pages that use the master page are merged with the new master page content the next time they are requested. Simply put, the master page model allows you to define a unified layout template (a master page), and the entire site responds to this change when it changes.
Add more pages to the site
Let's take a moment to add another page to the site to support an example of the final variety of courses. There will be more than 35 examples here, so let's create a section first. There will be many categories of examples, and in order to better manage these examples we add a folder to each category. Now we add three folders:
· Basicreporting
· Filtering
· Customformatting
Finally, add a new file to Solution Manager as shown in Figure 8. Each time you add a file, remember to check the "Select Motherboard page" checkbox.

Figure 8: Adding the following files

Step Three: Add site Map

One of the challenges of managing a Web site made up of a large number of Web pages is to provide a shortcut for visitors to browse the site. As a start, the navigation structure of the site must be defined. Next, the structure must be converted into user interface elements suitable for navigation, such as menu or location navigation. This process will be modified and corrected when a new page is added to the site and the existing page is removed.

Before ASP.net 2.0, the developer needed to create the site navigation structure, maintain it, and transform it into a user interface element suitable for navigation. In ASP.net 2.0, developers can take advantage of the very flexible and built-in site navigation system. The ASP.net 2.0 site navigation system allows developers to define a site map and provide an API to access that information.

The default ASP.net site map provider expects site map information to be stored in XML-formatted files. However, the site navigation system built on the provider model is a site map that can be extended to support multiple ways of storing. Jeff Prosise's article, the SQL site map Provider your ve Been waiting for shows how to create a provider that stores a site map in a SQL Server database; Another option is a file system based site map provider.
In this guide, we still use the default site map provider in asp.net2.0. To create a site map, right-click the project name in Solution Manager, select Add New Item, and then select the site map type. Name Web.sitemap and click the Add button.

Figure 9: Add a site map to your project

The site map file is an XML file. Note: Visual Studio can provide IntelliSense for the site map structure. The site map file must contain a <siteMap> as the root node and it must contain at least one <siteMapNode> child node. This <siteMapNode> element can also contain any number of <siteMapNode> child elements.

The site map simulates the file system. Add a <siteMapNode> element to each folder, and add a <siteMapNode> child element to each ASPX page:

Web.sitemap:

<?xml version= "1.0" encoding= "Utf-8"?> <sitemap xmlns= "http://schemas.microsoft.com/AspNet/" sitemap-file-1.0 "> <sitemapnode url=" ~/default.aspx "title=" Home "description=" Home "> <sitemapnode title = "Basic Reporting" url= "~/basicreporting/default.aspx" description= "Basic Reporting Samples" > <sitemapnode url= "~/basicreporting/simpledisplay.aspx" title= "Simple Display" description= "displays the complete contents of a Databa Se table. "/> <sitemapnode url= ~/basicreporting/declarativeparams.aspx" title= "declarative Parameters" Descrip Tion= "displays a subset of the contents of a database table using parameters."/> <sitemapnode url= "~/basicreport Ing/programmaticparams.aspx "title=" Setting Parameter values "description=" shows how to set Parameter the values program matically. "/> </siteMapNode> <sitemapnode title= filtering Reports" url= "~/filtering/default.aspx" descr Iption= "Samples of Reports that Support FilterinG "> <sitemapnode url=" ~/filtering/filterbydropdownlist.aspx "title=" Filter by Drop-down List "description=" Filt ER results using a drop-down list. "/> <sitemapnode url=" ~/filtering/masterdetailsdetails.aspx "title=" Master-Det Ails-details "description=" Filter results two levels down. "/> <sitemapnode url=" ~/filtering/detailsbyselecting. aspx "title=" Details of Selected Row "description=" Show detail results for a Selected item in a GridView./> < /sitemapnode> <sitemapnode title= "Customized formatting" url= "~/customformatting/default.aspx" description= "S Amples of Reports whose Formats are customized "> <sitemapnode url=" ~/customformatting/customcolors.aspx "title=" F Ormat Colors "description=" Format the grid s Colors based on the underlying data. "/> <sitemapnode url=" ~/cus Tomformatting/gridviewtemplatefield.aspx "title=" Custom Content in a GridView "description=" shows using the Templatefi Eld to customize the conTents of a field in a GridView. "/> <sitemapnode url=" ~/customformatting/detailsviewtemplatefield.aspx "title=" Custom Content in a DetailsView "description=" shows using the TemplateField to customize the contents of a field in a DetailsView. "/> <sitemapnode url=" ~/customformatting/formview.aspx "title=" Custom Content in a FormView "descr Iption= "illustrates using a FormView for a highly customized view."/> <sitemapnode url= "~/customformatting/summa Rydatainfooter.aspx "title=" Summary data in Footer "description=" Display Summary data in the grids Footer. "/> ;/sitemapnode> </siteMapNode> </siteMap>

The site map defines the navigation structure of the site, which is hierarchical to describe the various areas of the site. Each <siteMapNode> element in the Web.sitemap describes an area of a site structure.

Figure 10: The site map describes a hierarchical navigation structure

asp.net displays the structure of the site map through the Sitemap class in the dotnet framework. This class has a CurrentNode property that returns information about the node that the current user is accessing; The RootNode property returns the root node information of the site map (in our site map, home). CurrentNode the RootNode property returns SiteMapNode instances, SiteMapNode contains attributes such as Parentnode,childnodes,nextsibling,previoussibling, These properties allow the hierarchy of the site map to be traversed.

Step 4: Use the site map to display the menu

In asp.net 2.0 we can access data in a variety of ways, like ASP.net 1.x, and through new data source controls.
There are several built-in data source controls, such as SqlDataSource controls for accessing relational database data, Objectdatasoruce controls for accessing data provided by classes, and so on. You can also create your own custom data source controls.

The data source control acts as a proxy for your ASPX page and underlying data. To display the data that the data source control queries, we add another Web control to the page and bind it to the data source control. To bind a Web control to a data source control, simply set the DataSourceID property value of the Web control to the ID property value of the data source control.

To get the data from the site map, ASP.net provides the SiteMapDataSource control, which allows us to bind a Web control to display our sitemap. The TreeView and menu two Web controls are often used to provide a navigation user interface. To bind the data in the site map to the two controls, add a SiteMapDataSource control to the page, set the DataSourceID property value of the TreeView or menu control to the value of the ID property of the SiteMapDataSource control. For example, we can use the following tags to bring the menu control to the motherboard page:

<div id= "Navigation" >
 <asp:menu id= "Menu1" runat= "Server"
 datasourceid= "SiteMapDataSource1" >
 </asp:Menu>

 <asp:sitemapdatasource id= "SiteMapDataSource1" runat= "server"/>
</div >

In order to generate optimized HTML, we can bind the SiteMapDataSource control to the Repeater control, as follows:

 <div id= "navigation" > <ul> <li><asp:hyperlink runat= "Server" I D= "Lnkhome" navigateurl= "~/default.aspx" >Home</asp:HyperLink></li> <asp:repeater "Server"
   Id= "Menu" datasourceid= "SiteMapDataSource1" > <ItemTemplate> <li> <asp:hyperlink runat= "Server" Navigateurl= ' <%# eval ("Url")%> ' > <%# eval ("Title")%></asp:hyperlink> </li> </ite mtemplate> </asp:Repeater> </ul> <asp:sitemapdatasource id= "SiteMapDataSource1" runat= "Server" Sho Wstartingnode= "false"/> </div> 

The SiteMapDataSource control returns one level in the site map hierarchy at a time, starting at the root node in the site map (home in our site map), and then the next level (Basic reporting,filtering Reports and customized formatting) and so on.
When SiteMapDataSource is bound to repeater, it traverses the first level and displays each SiteMapNode instance of the first level with ItemTemplate. We can use the Eval (property name) to access the details of the SiteMapNode so that we can get the SiteMapNode URL and title property to the Hyperlink control.
The HTML tags generated above using the Repeater control example are shown below:

<li>
 <a href= "/code/basicreporting/default.aspx" >basic reporting</a>
</li>

<li>
 <a href= "/code/filtering/default.aspx" >filtering reports</a>
</li>

< li>
 <a href= "/code/customformatting/default.aspx" >
 customized formatting</a>
</li >

As you can see from the above, the second-level nodes of the site map (Basic reporting,filtering reports and customized formatting) are displayed rather than the first.

This is because the ShowStartingNode property of the SiteMapDataSource control is set to false, causing SiteMapDataSource to skip the root node of the site map instead of returning information from the second level of the level of the site map.
to display the sub-SiteMapNode of basic reporting,filtering reports and customized formatting, We can add another repeater to the ItemTemplate of the previous repeater. The second repeater is bound to the child node properties of the SiteMapNode instance, as follows:

<asp:repeater runat= "Server" id= "menu" datasourceid= "SiteMapDataSource1" >
 <ItemTemplate>
 < li>
  <asp:hyperlink runat= "Server"
  navigateurl= ' <%# eval ("Url")%> ' >
  <%# eval ("Title" )%></asp:hyperlink>

  <asp:repeater runat= "Server"
  datasource= ' <%# ((SiteMapNode) Container.DataItem). ChildNodes%> ' >
  <HeaderTemplate>
   <ul>
  </HeaderTemplate>

  < itemtemplate>
   <li>
   <asp:hyperlink runat= "Server"
    navigateurl= ' <%# Eval ("Url")%> ' >
    <%# Eval ("Title")%></asp:hyperlink>
   </li>
  </ItemTemplate>

  <FooterTemplate>
   </ul>
  </FooterTemplate>
  </asp:Repeater>
 </li >
 </ItemTemplate>
</asp:Repeater>

These two repeater generated HTML tags (to save space some tags are removed):

<li>
 <a href= "/code/basicreporting/default.aspx" >basic reporting</a>
 <ul>
 <li>
  <a href= "/code/basicreporting/simpledisplay.aspx" > Simple
  display</a>
 </li >
 <li>
  <a href= "/code/basicreporting/declarativeparams.aspx" >
  declarative Parameters </a>
 </li>
 <li>
  <a href= "/code/basicreporting/programmaticparams.aspx" >
  Setting Parameter values</a>
 </li>
 </ul>
</li>

<li>
 <a href= "/code/filtering/default.aspx" >filtering reports</a> ...
</li>

<li>
 <a href= "/code/customformatting/default.aspx" >
 Customized Formatting </a> ...
</li>

Use the CSS style chosen from Rachel Andrew's book: The CSS anthology:101 essential Tips, Tricks, & hacks,<ul> and <li> element styles will be displayed as follows:

Figure 11: Menu displayed with two repeater and some CSS

This menu is defined in the master page and is bound to the site map defined in Web.sitemap, which means that all site map modifications immediately reflect all pages that use the Site.master master page.

Turn off view state

All asp.net controls can keep their state at will, and in the original text, when the initial letter of the ViewState is not translated, it is serialized and saved in a hidden form field when the HTML is eventually generated. Controls use ViewState to remember the state in which they were changed by a program when the page returned, such as data that was bound by a Web control. If the view state allows information to be persisted when the page returns, it increases the size of the HTML code sent to the client, which can swell the page if there is no precise monitoring. Data display controls-especially the GridView control-can significantly increase the amount of extra markup to the page. Of course, these increases may have no effect on broadband users, but view state can add a few seconds of latency to dial-up users.

To observe the impact of view state, open the page in the browser and view the source code for the page (for Internet Explorer, click the "View" menu and select the Source option). You can also open the page tracking option to see the view state of each control on the page. The information for view state is serialized and placed in a hidden form field named _viewstate that is located in the <div> element following the <form> tag.

View state is persisted only when the form is used on the page; If your ASPX page does not contain
<form runat= "Server" > declaration, the resulting HTML tag will not contain ViewState hidden form fields.

The ViewState hidden form field generated by the master page is about 1800 bytes. These additional data are primarily generated by the data content provided by the SiteMapDataSource control for the Repeater control. Maybe 1800 bytes doesn't seem like much, but the view state that uses the GridView and uses a lot of fields and records can easily swell 10 times times or more.

You can set the EnableViewState property to False to turn off view state at the page level or at the control level, thereby reducing the size of the resulting markup. Web controls use view state to persist data that is bound to the data display control when the page returns, and when the view state of the data display control is turned off, the data must be rebind to the control each time the page returns. This responsibility falls to the developer at the time of ASP.net 1.x; in asp.net 2.0, when the page returns, the data display control will rebind the data when necessary.

Setting the EnableViewState of the Repeater control to false can reduce the view state of the page. Can be set through the Properties window or manually modified in code view. With these changes, the repeater tag will look like this:

<asp:repeater runat= "Server" id= "menu" datasourceid= "SiteMapDataSource1"
 enableviewstate= "False" >
 <ItemTemplate> ...
 <i>itemtemplate contents omitted for brevity</i>
 ... </ItemTemplate>
</asp:Repeater>

Through these changes, the page generated view state reduced to 52 bytes, reducing the 97% view state data! In this guide series I will turn off the view state of all data controls to reduce the size of the markup produced. In most cases, the EnableViewState property is set to false without prompting.

We discuss only when the data Web control must open its view state to provide the desired functionality.

Step 5: Add breadcrumb navigation

To complete the master page, let's add a breadcrumb navigation UI element to each page. Breadcrum navigation will quickly display the user's current location in the site. Adding a breadcrumb navigation in asp.net 2.0 is simple-just add a SiteMapPath control to the page and you don't need more code.
In our site, add this control to the header <div> tag:

<span class= "breadcrumb" >
 <asp:sitemappath id= "SiteMapPath1" runat= "Server" >
 </asp: Sitemappath>
</span>

The Breadcrum navigation control displays the page that the user is currently accessing and its parent node until it is to the root node (home in our site map).

Figure 12: The current page and its parent page displayed in the site map hierarchy using the position navigation control

Step 6: Add a default page to each section

In our site This course is divided into different classifications-basic reporting,filtering,custom formatting and so on-each category has a folder and has an ASPX page for the corresponding course. Also, each folder contains a Default.aspx page. In this default page, all courses in this section are displayed. For example, we can connect to simpledisplay.aspx,declarativeparams.aspx and programmaticparams.aspx through the Default.aspx page in the Basicreporting folder. Here, we can again use the Sitemap class and a data display control to display information about the site map defined in the Web.sitemap file.

Let's use repeater again to display an unordered list, but this time we'll show you the title and description of the guide. We need to repeat these tags and code on each default.aspx page, and we can encapsulate this UI logic into a user control. Add a folder named UserControls to the site and add a Web user control named Sectionleveltutoriallisting.ascx that contains the tags:

Figure 13: Adding a new Web user control to the UserControls folder

Sectionleveltutoriallisting.ascx

<%@ control language= "CS" autoeventwireup= "true"
 codefile= "SectionLevelTutorialListing.ascx.cs"
 inherits= "usercontrols_sectionleveltutoriallisting"%>
<asp:repeater id= "tutoriallist" runat= "Server" Enableviewstate= "False" >
 <HeaderTemplate><ul></HeaderTemplate>
 <itemtemplate >
 <li><asp:hyperlink runat= "Server"
  navigateurl= ' <%# Eval ("Url")%> '
  text= ' <%# Eval ("Title")%> ' ></asp:HyperLink>
  -<%# Eval ("Description")%></li>
 </ itemtemplate>
 <FooterTemplate></ul></FooterTemplate>
</asp:Repeater>

SectionLevelTutorialListing.ascx.cs

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;

public partial class Usercontrols_sectionleveltutoriallisting:usercontrol
{
 protected void Page_Load ( Object sender, EventArgs e)
 {
 //If sitemap.currentnode isn't null,
 //Bind CurrentNode childnodes to the GridView
 if (sitemap.currentnode!= null)
 {
  Tutoriallist.datasource = SiteMap.CurrentNode.ChildNodes ;
  Tutoriallist.databind ();}}

In the previous repeater example, I bound the Sitemap's data to repeater, and of course, this sectionleveltutoriallisting user control will also use this method. In the Page_Load event, there is a detection program to ensure that this is the first time the page is accessed (not returned) and that the URL of the page is mapped to a node in the site map. If the page uses this user control, then there is no corresponding
<sitemapnode>,sitemap.currentnode returns null and no data is bound to the Repeater control. Assuming we have a currentnode, I can bind its ChildNodes collection to this repeater. The Default.aspx page for each section is the parent of the tutorial in this section, which shows the links and descriptions of the tutorials in each section, with screenshots below:
Once this repeater is created, open the Default.aspx page of each folder in Design view and drag the user control to where you want it to appear.

Figure 14: The user control has been added to the Default.aspx page

Figure 15:basic The list of reporting guides

Summarize

After completing the site map and the master Sheet page, our tutorial site now has a unified page layout and navigation system. Although our site has many pages, we can centrally update the Site page layout and site navigation information. Specifically, the page layout information is defined in the master page Site.master, and the site map is defined in Web.sitemap. We do not need to write any code to complete the Site page layout and navigation mechanism, Visual Studio provides WYSIWYG design-time support.
Having completed the data access layer and business logic layer and defined a unified page layout and site navigation system, we will explore the common reporting pattern next. In the next three guides we will see basic report tasks-using Gridview,detailsview and FormView controls to display data obtained from the business logic layer.

I wish you a happy programming!

Author Introduction

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog Http://ScottOnWriting.NET.

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.