Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP.NET 2.0 Everyday Apps For Dummies (2006)

.pdf
Скачиваний:
57
Добавлен:
17.08.2013
Размер:
10.07 Mб
Скачать

Chapter 11: Building a Blog Application 407

Building the Leave Comment Page

The Leave Comment page lets a Web site visitor add a comment to a post. To see what this page looks like, flip back to Figure 11-5. The following sections present the .aspx file and the code-behind files for this page.

The Comment.aspx page

The .aspx file for the Leave Comment page is shown in Listing 11-10. This page displays the topic name in a FormView control at the top of the page. Then text boxes are used to get the user’s name and comment.

Listing 11-10: The Comment.aspx page

<%@ Page Language=”C#”

1

MasterPageFile=”~/MasterPage.master”

 

AutoEventWireup=”true”

 

CodeFile=”Comment.aspx.cs”

 

Inherits=”Comment”

 

Title=”Blog-O-Rama” %>

 

<asp:Content ID=”Content1” Runat=”Server”

2

ContentPlaceHolderID=”ContentPlaceHolder1” >

 

<table border=”0” width=”700” >

3

<tr>

 

<td width=”80” valign=”top”>

 

Your name:

 

</td>

 

<td width=”620” valign=”top”>

 

<asp:TextBox ID=”txtName” runat=”server”

4

Width=”400px”/>

 

</td>

 

</tr>

 

<tr>

 

<td width=”80” valign=”top”>

 

Your comment:

 

</td>

 

<td width=”620” valign=”top”>

 

<asp:TextBox ID=”txtComment” runat=”server”

5

TextMode=”MultiLine”

 

Height=”200px”

 

Width=”400px” />

 

</td>

 

</tr>

 

</table>

 

<asp:Button ID=”btnPost” runat=”server”

6

Text=”Post”

 

OnClick=”btnPost_Click” />

 

 

 

(continued)

408 Part V: Building Community Applications

Listing 11-10 (continued)

 

 

<asp:Button ID=”btnCancel” runat=”server”

7

 

 

Text=”Cancel”

 

 

 

OnClick=”btnCancel_Click”/>

8

 

 

<asp:SqlDataSource ID=”SqlDataSource1”

 

 

runat=”server”

 

 

 

ConnectionString

 

 

 

 

=”<%$ ConnectionStrings:BlogConnectionString %>”

 

 

 

InsertCommand=”INSERT INTO [Comments]

 

 

 

 

([postid], [username], [comment])

 

 

 

 

VALUES (@postid, @username, @comment)” >

 

 

 

<InsertParameters>

9

 

 

 

<asp:QueryStringParameter Name=”postid”

 

 

 

Type=”String”

 

 

 

 

QueryStringField=”postid” />

10

 

 

 

<asp:ControlParameter Name=”username”

 

 

 

Type=”String”

 

 

 

 

ControlID=”txtName”

 

 

 

 

PropertyName=”Text” />

11

 

 

 

<asp:ControlParameter Name=”comment”

 

 

 

Type=”String”

 

 

 

 

ControlID=”txtComment”

 

 

 

 

PropertyName=”Text” />

 

 

 

</InsertParameters>

 

 

 

</asp:SqlDataSource>

 

 

 

</asp:Content>

 

 

 

The critical lines of this listing are described in the following paragraphs:

 

 

1

Don’t forget to change the Language, AutoEventWireup, and

 

 

 

CodeFile attributes in the Page directive if you use Visual Basic

 

 

 

instead of C#.

 

 

 

2

The <Content> element provides the content that’s displayed for

 

 

 

the page.

 

 

 

3

This page uses an HTML table to manage the layout of its controls.

 

 

4

This text box lets the Web site visitor enter his or her name.

 

 

 

5

This multi-line text box lets the Web site visitor enter the text of

 

 

 

his or her comment.

 

 

 

6

The Web site visitor clicks this button to record the comment.

 

 

 

For this line and the next, you should remove the OnClick

 

 

 

 

attribute if you’re using Visual Basic instead of C#.

 

 

 

 

 

 

 

 

 

 

7 This button cancels the comment and returns to the Blog page. (Again, remove the OnClick attribute if you’re using VB instead of C#.)

8 Even though this page doesn’t contain any bound controls, it still uses SqlDataSource1 to insert the comment into the Comments table. The InsertCommand attribute specifies an INSERT statement that requires three parameters: postid, username, and comment.

Chapter 11: Building a Blog Application 409

9 The value of the postid parameter is obtained from the query string field named postid.

10 The username parameter is bound to the txtName text box.

11 The comment parameter is bound to the txtComment text box.

The code-behind file for the

Leave Comment page

Listings 11-11 and 11-12 show the C# and Visual Basic versions of the codebehind file for the Leave Comment page. As you can see, these code-behind files contain just two methods, which handle the click event for the Post and Cancel buttons.

Listing 11-11: The code-behind file for the Leave Comment page (C#)

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 Comment : System.Web.UI.Page

{

protected

void btnPost_Click(

1

object sender, EventArgs e)

 

{

 

 

SqlDataSource1.Insert();

 

Response.Redirect(“Blog.aspx?blog=”

 

+ Request.QueryString[“blog”]

 

+ “&post=”

 

+ Request.QueryString[“post”]);

 

}

 

 

protected void btnCancel_Click(

2

object sender, EventArgs e)

 

{

Response.Redirect(“Blog.aspx?blog=”

+ Request.QueryString[“blog”] + “&post=”

+ Request.QueryString[“post”]);

}

}

410 Part V: Building Community Applications

You’ll sleep better tonight if you read the following paragraphs, which describe the most important two lines of this code-behind file:

1 The btnPost_Click method executes when the user clicks the Post button. This method calls the Insert method of the data source to insert the comment into the Comments table. Then it redirects to the Blog.aspx page.

2 The btnCancel_Click method is similar to the btnPost_Click method, with one important exception: it doesn’t call the INSERT method of the data source. As a result, any comment entered by the user is ignored.

Listing 11-12: The code-behind file for the Leave Comment page (VB)

Partial Class Comment

 

Inherits System.Web.UI.Page

 

Protected Sub btnPost_Click( _

1

ByVal sender As Object, _

 

ByVal e As System.EventArgs) _

 

Handles btnPost.Click

 

SqlDataSource1.Insert()

 

Response.Redirect(“Blog.aspx?blog=” _

 

+ Request.QueryString(“blog”) _

 

+ “&post=” _

 

+ Request.QueryString(“post”))

 

End Sub

 

Protected Sub btnCancel_Click( _

2

ByVal sender As Object, _

 

ByVal e As System.EventArgs) _

 

Handles btnCancel.Click Response.Redirect(“Blog.aspx?blog=” _

+ Request.QueryString(“blog”) _ + “&post=” _

+ Request.QueryString(“post”))

End Sub End Class

Building the Login Page

The Login page is displayed if the user clicks the Login button provided by the Master Page or tries to access the My Blogs page without first logging in. The .aspx code for this page (pictured back in Figure 11-6) is shown in Listing 11-13.

 

 

Chapter 11: Building a Blog Application 411

 

 

 

Listing 11-13: The Login.aspx page

 

 

 

<%@ Page Language=”C#”

1

 

MasterPageFile=”~/MasterPage.master”

 

 

 

AutoEventWireup=”true”

 

 

 

CodeFile=”Login.aspx.cs”

 

 

 

Inherits=”Login”

 

 

 

Title=”Blog-O-Rama” %>

 

 

 

<asp:Content ID=”Content1” Runat=”Server”

2

 

ContentPlaceHolderID=”ContentPlaceHolder1” >

 

 

 

<asp:Login ID=”Login1” runat=”Server”

3

 

DestinationPageUrl=”~/Default.aspx”

 

 

TitleText=”Please enter your account information: <br /><br />”

CreateUserText=”New user?” CreateUserUrl=”~/Register.aspx” />

</asp:Content>

A quick list explains the details of three key lines in this listing:

1 Remember to change the Language, AutoEventWireup, and CodeFile attributes in the Page directive if you use Visual Basic.

2 The <Content> element provides the content that’s displayed for the page.

3 This page displays just one control, a Login control that lets the user enter a name and password to log in. For more information about how this control works, refer to Chapter 4.

Building the Register Page

The Register page is displayed if the user clicks the New User? link on the Login page or the Register link displayed by the Master Page. (To see what the Register page looks like, flip back to Figure 11-7.) The .aspx file for this page, which doesn’t require a code-behind file, is shown in Listing 11-14.

Listing 11-14: The Register.aspx page

<%@ Page Language=”C#”

1

AutoEventWireup=”true”

 

MasterPageFile=”~/MasterPage.master”

 

CodeFile=”Register.aspx.cs”

 

Inherits=”Register”

 

title=”Blog-O-Rama” %>

 

<asp:Content ID=”Content1” Runat=”Server”

2

 

 

(continued)

412 Part V: Building Community Applications

Listing 11-14 (continued)

ContentPlaceHolderID=”ContentPlaceHolder1” > <asp:CreateUserWizard ID=”CreateUserWizard1” 3

runat=”server” CreateUserButtonText=”Create Account”

ContinueDestinationPageUrl=”~\Admin\MyBlogs.aspx” > </asp:CreateUserWizard>

</asp:Content>

Here are the details of three key lines in this listing:

1 Remember to change the Language, AutoEventWireup, and CodeFile attributes in the Page directive if you use Visual Basic.

2 The <Content> element provides the content that’s displayed for the page.

3 This page displays just one control, a CreateUserWizard control that walks the user through the steps required to register a new user account. The ContinueDestinationPageUrl attribute provides the URL of the page to be displayed when the user completes the Wizard. In this case, the My Blogs page will be displayed. (For more information about how the CreateUserWizard control works, refer to Chapter 4.)

Building the My Blogs Page

The My Blogs page was originally shown back in Figure 11-8. It is similar to the Blog Home page (Default.aspx), with four key differences:

1.It’s stored in the \Admin folder, which is protected from anonymous access. That means that only users who have registered and logged in can view it.

2.Rather than display all of the blogs in the Blogs table, it displays only the blogs that were created by the current user.

3.It includes a link that takes the user to the Post page to add a new post to one of his or her blogs.

4.It includes controls that let the user create a new blog.

The following sections present the .aspx code and code-behind files for this page.

Chapter 11: Building a Blog Application 413

The MyBlogs.aspx page

The .aspx file for the My Blogs page is shown in Listing 11-15. It includes a GridView control to display the user’s blogs and a set of text boxes, field validators, and buttons that enable the user to create a new blog. In addition, two SqlDataSource controls are used.

Listing 11-15: The My Blogs page (MyBlogs.aspx)

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”MyBlogs.aspx.cs” Inherits=”MyBlogs”

Title=”My Blogs” %>

<asp:Content ID=”Content1” Runat=”Server” ContentPlaceHolderID=”ContentPlaceHolder1” > <h2>My Blogs</h2>

<asp:GridView ID=”GridView1” runat=”server” AllowPaging=”True” AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1”>

<Columns>

<asp:TemplateField>

<HeaderTemplate> Blog

</HeaderTemplate>

<ItemTemplate>

<b>

<asp:LinkButton ID=”LinkButton1” runat=”server”

Text=’<% #Bind(“name”) %>’ PostBackUrl=’<% #Bind(“blogid”,

“~\Blog.aspx?blog={0}”) %>’ CausesValidation=”False” />

<br />

<asp:Label ID=”Label2” runat=”server” Text=’<% #Bind(“description”) %>’ />

</ItemTemplate>

<HeaderStyle HorizontalAlign=”Left” /> <ItemStyle HorizontalAlign=”Left”

Width=”250px” /> </asp:TemplateField>

<asp:BoundField

DataField=”username”

1

2

3

4

5

(continued)

414 Part V: Building Community Applications

Listing 11-15 (continued)

HeaderText=”Owner” >

 

<HeaderStyle HorizontalAlign=”Left” />

 

<ItemStyle Width=”100px” />

 

</asp:BoundField>

 

<asp:BoundField

6

DataField=”posts”

 

HeaderText=”Posts” >

 

<HeaderStyle HorizontalAlign=”Left” />

 

<ItemStyle Width=”80px” />

 

</asp:BoundField>

 

<asp:HyperLinkField

7

DataNavigateUrlFields=”blogid”

 

DataNavigateUrlFormatString

 

=”NewPost.aspx?blog={0}”

 

Text=”New Post”>

 

<ItemStyle Width=”70px” />

 

</asp:HyperLinkField>

 

</Columns>

 

</asp:GridView>

 

<asp:SqlDataSource ID=”SqlDataSource1”

8

runat=”server”

 

ConnectionString

 

=”<%$ ConnectionStrings:BlogConnectionString %>”

SelectCommand=”SELECT [blogid], [name],

 

[description], [username], [posts]

 

FROM [Blogs]

 

WHERE [username]=@username

 

ORDER BY [name]”>

 

<SelectParameters>

 

<asp:Parameter Name=”username”

9

Type=”String” />

 

</SelectParameters>

 

</asp:SqlDataSource>

 

<br />To create a new blog:<br />

 

<asp:Label ID=”Label3” runat=”server”

10

BorderStyle=”None” Text=”Blog name:”

 

Width=”80px” />

 

<asp:TextBox ID=”txtBlogName” runat=”server” />

 

<asp:RequiredFieldValidator

 

ID=”RequiredFieldValidator1” runat=”server”

 

ControlToValidate=”txtBlogName”

 

Display=”Dynamic”

 

ErrorMessage=”Required.” /><br />

 

<asp:Label ID=”Label4” runat=”server”

11

BorderStyle=”None” Text=”Description:”

 

Width=”80px” />

 

 

 

Chapter 11: Building a Blog Application 415

<asp:TextBox ID=”txtDescription” runat=”server” /> <asp:RequiredFieldValidator

ID=”RequiredFieldValidator2” runat=”server” ControlToValidate=”txtDescription” Display=”Dynamic”

ErrorMessage=”Required.” /><br />

<asp:Button ID=”btnCreate” runat=”server”

12

OnClick=”btnCreate_Click”

 

Text=”Create Blog” />

 

<asp:SqlDataSource ID=”SqlDataSource2”

13

runat=”server”

 

ConnectionString

 

=”<%$ ConnectionStrings:BlogConnectionString %>”

InsertCommand=”INSERT INTO [Blogs]

 

([username], [name], [description])

 

VALUES (@username, @name, @description)” >

 

<InsertParameters>

14

<asp:Parameter

Name=”username” Type=”String” /> <asp:Parameter

Name=”name” Type=”String” /> <asp:Parameter

Name=”description” Type=”String” /> </InsertParameters>

</asp:SqlDataSource>

</asp:Content>

The following paragraphs describe the important lines of this listing:

1 You must change the Language, AutoEventWireup, and

CodeFile attributes in the Page directive if you use Visual Basic instead of C#.

2 The <Content> element provides the content that’s displayed for the page.

3 The GridView control lists the blogs retrieved from the Blogs table by the SQL data source named SqlDataSource1. Although it’s unlikely that any user will have more than a few blogs (most will have only one), paging is enabled for this GridView control.

4 The first column of the GridView control is a template column that specifies two templates:

A header template displays the word Blog as the column heading.

An item template displays the blog name and title; a link button displays the blog name. Binding expressions are used for the

Text and PostBackUrl attributes.

416 Part V: Building Community Applications

5 The second column is a bound column that displays the username field.

6 The third column control is a bound column that displays the number of posts for the blog, as indicated by the posts field.

7 The fourth column is a hyperlink field that provides a link to the NewPost.aspx page so the user can create a new post. A format string provides a value for the blog query string.

8 The SqlDataSource1 data source uses a SELECT statement to retrieve five columns — blogid, name, description, username, and posts — for the user indicated by the username parameter.

9 The username parameter is defined as a standard parameter. Its value will be supplied in the Page_Load method of the codebehind file.

10 This label, text box, and RequiredFieldValidator let the user enter the name for a new blog.

11 This label, text box, and RequiredFieldValidator let the user enter the description for a new blog.

12 The Create button lets the user create a new blog using the name

and description entered in the text boxes.

If you’re using Visual Basic, you should remove the OnClick attribute.

13 The second data source (SqlDataSource2) provides the INSERT statement used to create a new blog.

14 The INSERT statement uses three parameters — username, name, and description — whose values will be set in the codebehind file.

The code-behind file for the My Blogs page

Listings 11-16 and 11-17 show the C# and Visual Basic versions of the codebehind file for the My Blogs page. As you can see, it consists of just two methods: Page_Load (executed when the page loads) and btnCreate_Click, executed when the user creates a new blog.

Listing 11-16: The code-behind file for the My Blogs page (C# version)

using System; using System.Data;

using System.Configuration; using System.Collections;