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

ASP.NET 2.0 Everyday Apps For Dummies (2006)

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

Chapter 9: Building a Content Management System 317

The code-behind file for the Content List page

The List.aspx page requires a code-behind file to show or hide the Add link — depending on the user’s departmental role(s) — and to handle the Click event for the Add link. The C# version of this code-behind file is shown in Listing 9-7, and Listing 9-8 shows the Visual Basic version.

Listing 9-7: The code-behind file for the Content List 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 List : System.Web.UI.Page

 

{

 

protected void Page_Load(

1

object sender, EventArgs e)

 

{

 

string deptid =

 

(String)Request.QueryString[“dept”];

 

if (User.IsInRole(deptid))

 

btnAdd.Visible = true;

 

else

 

btnAdd.Visible = false;

 

}

 

protected void btnAdd_Click(

2

object sender, EventArgs e)

 

{

Response.Redirect(“Detail.aspx?item=-1&type=”

+Request.QueryString[“type”]

+“&dept=” + Request.QueryString[“dept”]);

}

}

318 Part V: Building Community Applications

Here’s how the two methods work in this code-behind file:

1

2

Page_Load: This method begins by retrieving the department ID from the dept query string. Then, it calls User.IsInRole to find out if the user is an administrator for the department. If so, the Add link is made visible; if not, it’s hidden.

btnAdd_Click: This method is called when the user clicks the Add link. It redirects to the Detail.aspx page, setting the item query string to -1 to indicate that a new row should be inserted. The redirect URL also includes query strings that pass the con- tent-type ID and the department ID.

Listing 9-8: The code-behind file for the Content List page (VB)

Partial Class List

Inherits System.Web.UI.Page

 

Protected Sub Page_Load( _

1

ByVal sender As Object, _

 

ByVal e As System.EventArgs) _

 

Handles Me.Load

 

Dim deptid As String

 

deptid = Request.QueryString(“dept”)

 

If User.IsInRole(deptid) Then

 

btnAdd.Visible = True

 

Else

 

btnAdd.Visible = False

 

End If

 

End Sub

 

Protected Sub btnAdd_Click( _

2

ByVal sender As Object, _

 

ByVal e As System.EventArgs) _

 

Handles btnAdd.Click

Response.Redirect(“Detail.aspx?item=-1&type=” _

+Request.QueryString(“type”) _

+“&dept=” + Request.QueryString(“dept”))

End Sub

End Class

Building the Content Detail Page

The last page for this application is the Content Detail page, pictured way back in Figure 9-6. This page displays the content item selected by the user; if the user is an administrator for the current department, the page lets the user edit or delete the item — or insert a new content item.

This page uses three query string fields. A typical request looks like this:

Chapter 9: Building a Content Management System 319

Detail.aspx?item=3&type=faq&dept=hr

Here, content item 3 is requested. The Content Detail page itself doesn’t need the type and dept values, but passing them as query string fields makes it easier for the detail page to display the department name in the heading area — and these values are required to insert a content item.

Speaking of inserting rows, the special value -1 is used in the item query string field to indicate that a new content item should be inserted. For example, to create a new FAQ for the Human Resources department, the request string looks like this:

Detail.aspx?item=-1&type=faq&dept=hr

The following sections present the .aspx code for the Content Details page, as well as both the C# and VB versions of the required code-behind file.

The Detail.aspx file

Listing 9-9 shows the .aspx code for the Content Details page.

Listing 9-9: The Content Details page (Detail.aspx)

<%@ Page Language=”C#”

1

MasterPageFile=”~/MasterPage.master”

 

AutoEventWireup=”true”

 

CodeFile=”Detail.aspx.cs”

 

Inherits=”Detail”

 

Title=”Company Intranet” %>

2

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

ContentPlaceHolderID=”ContentPlaceHolder1” >

3

<asp:FormView ID=”FormView2” runat=”server”

DataSourceID=”SqlDataSource1”>

 

<ItemTemplate>

 

<h1>

4

<asp:Label ID=”nameLabel”

runat=”server”

 

Text=’<%# Eval(“name”) %>’ /><br />

 

</h1>

 

</ItemTemplate>

 

</asp:FormView>

5

<asp:SqlDataSource ID=”SqlDataSource1”

runat=”server”

 

ConnectionString=”<%$ ConnectionStrings:

 

ConnectionString %>”

SelectCommand=”SELECT [name] FROM Departments

WHERE deptid = @deptid” >

(continued)

320 Part V: Building Community Applications

Listing 9-9 (continued)

<SelectParameters>

<asp:QueryStringParameter

Name=”deptid” QueryStringField=”dept” />

</SelectParameters>

</asp:SqlDataSource>

</asp:Content>

<asp:Content ID=”Content2” Runat=”Server” ContentPlaceHolderID=”ContentPlaceHolder2” > <asp:DetailsView ID=”DetailsView1”

runat=”server”

AutoGenerateRows=”False”

DataSourceID=”SqlDataSource2”

DataKeyNames=”contentid”

BorderStyle=”None” Height=”50px” Width=”350px”

OnItemDeleted=”DetailsView1_ItemDeleted” OnItemInserted=”DetailsView1_ItemInserted” OnItemCommand=”DetailsView1_ItemCommand” >

<Fields>

<asp:TemplateField ShowHeader=”True” HeaderText=”Title:” HeaderStyle-Width=”80px” HeaderStyle-VerticalAlign=”Top” >

<ItemTemplate>

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

Text=’<%# Eval(“title”) %>’ ReadOnly=”True” Width=”250px” />

</ItemTemplate>

<EditItemTemplate>

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

Text=’<%# Bind(“title”) %>’ Width=”250px” BackColor=”LightBlue” />

<asp:RequiredFieldValidator

ID=”RequiredFieldValidator1”

runat=”server”

ControlToValidate=”txtEditTitle” ErrorMessage=”Title is required.” Display=”Dynamic” />

</EditItemTemplate>

<InsertItemTemplate>

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

Text=’<%# Bind(“title”) %>’ Width=”250px” BackColor=”LightBlue” />

<asp:RequiredFieldValidator

ID=”RequiredFieldValidator2”

runat=”server”

6

7

8

9

10

11

12

Chapter 9: Building a Content Management System 321

ControlToValidate=”txtInsertTitle”

 

ErrorMessage=”Title is required.”

 

Display=”Dynamic” />

 

</InsertItemTemplate>

 

</asp:TemplateField>

13

<asp:TemplateField ShowHeader=”True”

HeaderText=”Text:”

 

HeaderStyle-Width=”80px”

 

HeaderStyle-VerticalAlign=”Top” >

14

<ItemTemplate>

<asp:TextBox ID=”txtItemContent”

 

runat=”server”

 

Text=’<%# Eval(“content”) %>’

 

ReadOnly=”True”

 

TextMode=”MultiLine”

 

Width=”250px” Height=”200px” /><br />

</ItemTemplate>

15

<EditItemTemplate>

<asp:TextBox ID=”txtEditContent”

 

runat=”server”

 

Text=’<%# Bind(“content”) %>’

 

TextMode=”MultiLine”

 

Width=”250px” Height=”200px”

 

BackColor=”LightBlue” /><br />

 

<asp:RequiredFieldValidator

 

ID=”RequiredFieldValidator3”

 

runat=”server”

 

ControlToValidate=”txtEditContent”

 

ErrorMessage=”Text is required.”

 

Display=”Dynamic” />

 

</EditItemTemplate>

16

<InsertItemTemplate>

<asp:TextBox ID=”txtInsertContent”

 

runat=”server”

 

Text=’<%# Bind(“content”) %>’

 

TextMode=”MultiLine”

 

Width=”250px” Height=”200px”

 

BackColor=”LightBlue” /><br />

 

<asp:RequiredFieldValidator

 

ID=”RequiredFieldValidator4”

 

runat=”server”

 

ControlToValidate=”txtInsertContent”

 

ErrorMessage=”Text is required.”

 

Display=”Dynamic” />

 

</InsertItemTemplate>

 

</asp:TemplateField>

 

</Fields>

 

</asp:DetailsView>

17

<asp:SqlDataSource ID=”SqlDataSource2”

runat=”server”

 

ConnectionString=”<%$ ConnectionStrings:

 

ConnectionString %>”

 

OldValuesParameterFormatString=”original_{0}”

 

 

 

(continued)

322 Part V: Building Community Applications

Listing 9-9 (continued)

SelectCommand=”SELECT

18

[contentid],

 

[title],

 

[content]

 

FROM [ContentItems]

 

WHERE ([contentid] = @contentid)”

 

UpdateCommand=”UPDATE [ContentItems]

19

SET [title] = @title,

 

[content] = @content

 

WHERE [contentid] = @original_contentid”

 

DeleteCommand=”DELETE

20

FROM [ContentItems]

 

WHERE [contentid] = @original_contentid”

 

InsertCommand=”INSERT

21

INTO [ContentItems]

 

([title], [content], [typeid], [deptid])

 

VALUES (@title, @content, @typeid, @deptid)” >

<SelectParameters>

22

<asp:QueryStringParameter

 

Name=”contentid”

 

QueryStringField=”item”

 

Type=”Int32” />

 

</SelectParameters>

 

<UpdateParameters>

23

<asp:Parameter Name=”title”

 

Type=”String” />

 

<asp:Parameter Name=”content”

 

Type=”String” />

 

<asp:Parameter Name=”original_contentid”

 

Type=”Int32” />

 

</UpdateParameters>

 

<DeleteParameters>

24

<asp:Parameter Name=”original_contentid”

 

Type=”Int32” />

 

</DeleteParameters>

 

<InsertParameters>

25

<asp:Parameter Name=”title”

 

Type=”String” />

 

<asp:Parameter Name=”content”

 

Type=”String” />

 

<asp:QueryStringParameter Name=”deptid”

 

QueryStringField=”dept” Type=”String” />

<asp:QueryStringParameter Name=”typeid”

 

QueryStringField=”type” Type=”String” />

</InsertParameters>

 

</asp:SqlDataSource>

 

<br />

 

<asp:LinkButton ID=”btnReturn”

26

runat=”server”

 

Text=”Return to list”

 

OnClick=”btnReturn_Click” />

 

</asp:Content>

 

Chapter 9: Building a Content Management System 323

Brace yourself — the following paragraphs describe the 26 essential tenets of this listing:

1 You will need to change this Page directive if you use the VB version of the code-behind file. Specifically, you’ll need to change the

Language, AutoEventWireup, and CodeFile attributes to VB,

False, and Detail.aspx.vb.

2 The first <Content> element displays the department name at the top of the page.

3 This FormView is bound to the SqlDataSource1 data source and displays the department name.

4 This Label control displays the name field.

5 The first SQL data source (SqlDataSource1) retrieves the department name, using a parameter named deptid to specify the department to retrieve.

6 The deptid parameter is a query parameter, taking its value from the dept query string.

7 The second <Content> element provides the main content for the page.

8 The DetailsView control displays the title and text for the selected content item, which is retrieved by the SqlDataSource2 data source.

If you’re working in Visual Basic, you should drop the

OnItemDeleted, OnItemInserted, or OnItemCommand attributes.

9 This <TemplateField> element is the first of two fields contained in the <Fields> element for the DetailsView control.

10 The Item template is used to display the content item’s title when the DetailsView control is displayed in Read-Only mode. It consists of a single read-only text box that uses the Eval method to bind to the title field of the data source.

11 The EditItem template is displayed when the user clicks the Edit link to edit a content item. It includes two controls: a text box that uses the Bind method to bind to the title field, and a RequiredFieldValidator that ensures that the user enters a value for the title. (Notice that the background color for the text box is set to blue to provide a visual clue that the page is in Edit mode.)

12 The InsertItem template is displayed when the DetailsView control enters Insert mode. That happens when the Details.aspx page is called with -1 as the value of the item query string. This

324 Part V: Building Community Applications

template contains the same text box and RequiredField Validator controls as the EditItem template.

13 This <TemplateField> field is the second field contained in the <Fields> element for the DetailsView control. It displays the content item’s text.

14 The item template displays the text in Read-Only mode. It uses a read-only text box that (in turn) uses the Eval method to bind to the text field. Notice that the text box allows multiple lines and is 200 pixels high.

15 The EditItem template provides a text box that binds to the text field and to a RequiredFieldValidator.

16 The InsertItem template contains the same text box and

RequiredFieldValidator controls as the EditItem template.

17 The SqlDataSource2 data source provides the SQL statements necessary to retrieve, update, delete, and insert rows in the ContentItems table.

18 The SELECT statement retrieves the contentid, title, and content fields for the content item specified by the contentid parameter.

19 The UPDATE statement updates the title and content fields with values provided by the title and content parameters.

20 The DELETE statement deletes the content item indicated by the contentid parameter.

21 The INSERT statement inserts a new item into the ContentItems table.

22 The <SelectParameters> element specifies that the contentid parameter gets its value from the item query string.

23 The <UpdateParameters> element provides the parameters necessary to execute the UPDATE statement.

24 The <DeleteParameters> element provides the parameters necessary to execute the DELETE statement.

25 The <InsertParameters> element provides the parameters necessary to execute the INSERT statement.

26 The LinkButton control returns the user to the Content List page.

If you’re working in Visual Basic, you’ll want to remove the OnClick attribute.

Chapter 9: Building a Content Management System 325

The code-behind file for the Content Detail page

Like the List.aspx page, the Detail.aspx page requires a code-behind file. The C# version of this code-behind file is shown in Listing 9-10, and Listing 9-11 shows the Visual Basic version.

Listing 9-10: The code-behind file for the Content Detail 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 Detail : System.Web.UI.Page

 

{

 

 

string deptid;

 

string typeid;

 

protected void Page_Load(

1

 

object sender, EventArgs e)

 

{

 

 

 

deptid = (String)Request.QueryString[“dept”];

 

 

typeid = (string)Request.QueryString[“type”];

 

 

if (User.IsInRole(deptid))

 

 

{

 

DetailsView1.AutoGenerateDeleteButton = true; DetailsView1.AutoGenerateEditButton = true; if (Request.QueryString[“item”] == “-1”)

{

DetailsView1.DefaultMode

= DetailsViewMode.Insert; DetailsView1.AutoGenerateInsertButton =

true;

}

}

else

{

DetailsView1.AutoGenerateDeleteButton = false; DetailsView1.AutoGenerateEditButton = false;

(continued)

326 Part V: Building Community Applications

Listing 9-10 (continued)

}

}

protected void DetailsView1_ItemDeleted(

object sender, DetailsViewDeletedEventArgs e)

{

Response.Redirect(“List.aspx?type=” + typeid + “&dept=” + deptid);

}

protected void DetailsView1_ItemInserted(

object sender, DetailsViewInsertedEventArgs e)

{

Response.Redirect(“List.aspx?type=” + typeid + “&dept=” + deptid);

}

protected void DetailsView1_ItemCommand(

object sender, DetailsViewCommandEventArgs e)

{

if (e.CommandName==”Cancel”)

if (DetailsView1.DefaultMode

== DetailsViewMode.Insert) Response.Redirect(

“List.aspx?type=” + typeid + “&dept=” + deptid);

}

protected void btnReturn_Click( object sender, EventArgs e)

{

Response.Redirect(“List.aspx?type=” + typeid + “&dept=” + deptid);

}

}

2

3

4

5

To end the suspense, the following paragraphs explain the purpose of each method in this code-behind file:

1 Page_Load: This method is called each time the page is loaded. It starts by extracting the values of the dept and type query string fields and saving them in class instance variables named deptid and typeid.

Next, it calls User.IsInRole to determine if the user is an administrator for the current department. If so, the DetailsView control is configured to automatically generate Update and Delete links. Otherwise the DetailsView control is configured to suppress the Update and Delete links.