Part 7: Adding Features
by Joe Stagner
Tailspin Spyworks demonstrates how extraordinarily simple it is to create powerful, scalable applications for the .NET platform. It shows off how to use the great new features in ASP.NET 4 to build an online store, including shopping, checkout, and administration.
This tutorial series details all of the steps taken to build the Tailspin Spyworks sample application. Part 7 adds additional features, such as account review, product reviews, and “popular items” and “also purchased” user controls.
Adding Features
Though users can browse our catalog, place items in their shopping cart, and complete the checkout process, there are a number of supporting features that we will include to improve our site.
- Account Review (List orders placed and view details.)
- Add some context specific content to the front page.
- Add a feature to let users Review the products in the catalog.
- Create a User Control to display Popular Items and Place that control on the front page.
- Create an “Also Purchased” user control and add it to the product details page.
- Add a Contact Page.
- Add an About Page.
- Global Error
Account Review
In the “Account” folder create two .aspx pages one named OrderList.aspx and the other named OrderDetails.aspx
OrderList.aspx will leverage the GridView and EntityDataSoure controls much as we have previously.
[!code-aspxMain]
1: <div class="ContentHead">Order History</div><br />
2:
3: <asp:GridView ID="GridView_OrderList" runat="server" AllowPaging="True"
4: ForeColor="#333333" GridLines="None" CellPadding="4" Width="100%"
5: AutoGenerateColumns="False" DataKeyNames="OrderID"
6: DataSourceID="EDS_Orders" AllowSorting="True" ViewStateMode="Disabled" >
7: <AlternatingRowStyle BackColor="White" />
8: <Columns>
9: <asp:BoundField DataField="OrderID" HeaderText="OrderID" ReadOnly="True"
10: SortExpression="OrderID" />
11: <asp:BoundField DataField="CustomerName" HeaderText="Customer"
12: SortExpression="CustomerName" />
13: <asp:BoundField DataField="OrderDate" HeaderText="Order Date"
14: SortExpression="OrderDate" />
15: <asp:BoundField DataField="ShipDate" HeaderText="Ship Date"
16: SortExpression="ShipDate" />
17: <asp:HyperLinkField HeaderText="Show Details" Text="Show Details"
18: DataNavigateUrlFields="OrderID"
19: DataNavigateUrlFormatString="~/Account/OrderDetails.aspx?OrderID={0}" />
20: </Columns>
21: <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
22: <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
23: <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
24: <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
25: <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
26: <SortedAscendingCellStyle BackColor="#FDF5AC" />
27: <SortedAscendingHeaderStyle BackColor="#4D0000" />
28: <SortedDescendingCellStyle BackColor="#FCF6C0" />
29: <SortedDescendingHeaderStyle BackColor="#820000" />
30: <SortedAscendingCellStyle BackColor="#FDF5AC"></SortedAscendingCellStyle>
31: <SortedAscendingHeaderStyle BackColor="#4D0000"></SortedAscendingHeaderStyle>
32: <SortedDescendingCellStyle BackColor="#FCF6C0"></SortedDescendingCellStyle>
33: <SortedDescendingHeaderStyle BackColor="#820000"></SortedDescendingHeaderStyle>
34: </asp:GridView>
35:
36: <asp:EntityDataSource ID="EDS_Orders" runat="server" EnableFlattening="False"
37: AutoGenerateWhereClause="True"
38: Where=""
39: OrderBy="it.OrderDate DESC"
40: ConnectionString="name=CommerceEntities"
41: DefaultContainerName="CommerceEntities"
42: EntitySetName="Orders" >
43: <WhereParameters>
44: <asp:SessionParameter Name="CustomerName" SessionField="UserName" />
45: </WhereParameters>
46: </asp:EntityDataSource>
The EntityDataSoure selects records from the Orders table filtered on the UserName (see the WhereParameter) which we set in a session variable when the user log’s in.
Note also these parameters in the HyperlinkField of the GridView:
[!code-xmlMain]
1: DataNavigateUrlFields="OrderID" DataNavigateUrlFormatString="~/Account/OrderDetails.aspx?OrderID={0}"
These specify the link to the Order details view for each product specifying the OrderID field as a QueryString parameter to the OrderDetails.aspx page.
OrderDetails.aspx
We will use an EntityDataSource control to access the Orders and a FormView to display the Order data and another EntityDataSource with a GridView to display all the Order’s line items.
[!code-aspxMain]
1: <asp:FormView ID="FormView1" runat="server" CellPadding="4"
2: DataKeyNames="OrderID"
3: DataSourceID="EDS_Order" ForeColor="#333333" Width="250px">
4: <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
5: <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
6: <ItemTemplate>
7: OrderID : <%# Eval("OrderID") %><br />
8: CustomerName : <%# Eval("CustomerName") %><br />
9: Order Date : <%# Eval("OrderDate") %><br />
10: Ship Date : <%# Eval("ShipDate") %><br />
11: </ItemTemplate>
12: <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
13: <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
14: </asp:FormView>
15: <asp:EntityDataSource ID="EDS_Order" runat="server" EnableFlattening="False"
16: ConnectionString="name=CommerceEntities"
17: DefaultContainerName="CommerceEntities"
18: EntitySetName="Orders"
19: AutoGenerateWhereClause="True"
20: Where=""
21: EntityTypeFilter="" Select="">
22: <WhereParameters>
23: <asp:QueryStringParameter Name="OrderID" QueryStringField="OrderID" Type="Int32" />
24: </WhereParameters>
25: </asp:EntityDataSource>
26:
27: <asp:GridView ID="GridView_OrderDetails" runat="server"
28: AutoGenerateColumns="False"
29: DataKeyNames="ProductID,UnitCost,Quantity"
30: DataSourceID="EDS_OrderDetails"
31: CellPadding="4" GridLines="Vertical" CssClass="CartListItem"
32: onrowdatabound="MyList_RowDataBound" ShowFooter="True"
33: ViewStateMode="Disabled">
34: <AlternatingRowStyle CssClass="CartListItemAlt" />
35: <Columns>
36: <asp:BoundField DataField="ProductID" HeaderText="Product ID" ReadOnly="True"
37: SortExpression="ProductID" />
38: <asp:BoundField DataField="ModelNumber" HeaderText="Model Number"
39: SortExpression="ModelNumber" />
40: <asp:BoundField DataField="ModelName" HeaderText="Model Name"
41: SortExpression="ModelName" />
42: <asp:BoundField DataField="UnitCost" HeaderText="Unit Cost" ReadOnly="True"
43: SortExpression="UnitCost" DataFormatString="{0:c}" />
44: <asp:BoundField DataField="Quantity" HeaderText="Quantity" ReadOnly="True"
45: SortExpression="Quantity" />
46: <asp:TemplateField>
47: <HeaderTemplate>Item Total</HeaderTemplate>
48: <ItemTemplate>
49: <%# (Convert.ToDouble(Eval("Quantity")) * Convert.ToDouble(Eval("UnitCost")))%>
50: </ItemTemplate>
51: </asp:TemplateField>
52: </Columns>
53: <FooterStyle CssClass="CartListFooter"/>
54: <HeaderStyle CssClass="CartListHead" />
55: </asp:GridView>
56: <asp:EntityDataSource ID="EDS_OrderDetails" runat="server"
57: ConnectionString="name=CommerceEntities"
58: DefaultContainerName="CommerceEntities"
59: EnableFlattening="False"
60: EntitySetName="VewOrderDetails"
61: AutoGenerateWhereClause="True"
62: Where="">
63: <WhereParameters>
64: <asp:QueryStringParameter Name="OrderID" QueryStringField="OrderID" Type="Int32" />
65: </WhereParameters>
66: </asp:EntityDataSource>
In the Code Behind file (OrderDetails.aspx.cs) we have two little bits of housekeeping.
First we need to make sure that OrderDetails always gets an OrderId.
[!code-csharpMain]
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: if (String.IsNullOrEmpty(Request.QueryString["OrderId"]))
4: {
5: Response.Redirect("~/Account/OrderList.aspx");
6: }
7: }
We also need to calculate and display the order total from the line items.
[!code-csharpMain]
1: decimal _CartTotal = 0;
2:
3: protected void MyList_RowDataBound(object sender, GridViewRowEventArgs e)
4: {
5: if (e.Row.RowType == DataControlRowType.DataRow)
6: {
7: TailspinSpyworks.Data_Access.VewOrderDetail myCart = new
8: Data_Access.VewOrderDetail();
9: myCart = (TailspinSpyworks.Data_Access.VewOrderDetail)e.Row.DataItem;
10: _CartTotal += Convert.ToDecimal(myCart.UnitCost * myCart.Quantity);
11: }
12: else if (e.Row.RowType == DataControlRowType.Footer)
13: {
14: e.Row.Cells[5].Text = "Total: " + _CartTotal.ToString("C");
15: }
16: }
The Home Page
Let’s add some static content to the Default.aspx page.
First I’ll create a “Content” folder and within it an Images folder (and I’ll include an image to be used on the home page.)
Into the bottom placeholder of the Default.aspx page, add the following markup.
[!code-aspxMain]
1: <h2>
2: <asp:LoginView ID="LoginView_VisitorGreeting" runat="server">
3: <AnonymousTemplate>
4: Welcome to the Store !
5: </AnonymousTemplate>
6: <LoggedInTemplate>
7: Hi <asp:LoginName ID="LoginName_Welcome" runat="server" />. Thanks for coming back.
8: </LoggedInTemplate>
9: </asp:LoginView>
10: </h2>
11:
12: <p><strong>TailSpin Spyworks</strong> demonstrates how extraordinarily simple it is to create powerful, scalable applications for the .NET platform. </p>
13: <table>
14: <tr>
15: <td>
16: <h3>Some Implementation Features.</h3>
17: <ul>
18: <li><a href="#">CSS Based Design.</a></li>
19: <li><a href="#">Data Access via Linq to Entities.</a></li>
20: <li><a href="#">MasterPage driven design.</a></li>
21: <li><a href="#">Modern ASP.NET Controls User.</a></li>
22: <li><a href="#">Integrated Ajac Control Toolkit Editor.</a></li>
23: </ul>
24: </td>
25: <td>
26: <img src="Content/Images/SampleProductImage.gif" alt=""/>
27: </td>
28: </tr>
29: </table>
30:
31: <table>
32: <tr>
33: <td colspan="2"><hr /></td>
34: </tr>
35: <tr>
36: <td>
37: <!-- Popular Items -->
38: </td>
39: <td>
40: <center><h3>Ecommerce the .NET 4 Way</h3></center>
41: <blockquote>
42: <p>
43: ASP.NET offers web developers the benefit of more that a decade of innovation.
44: This demo leverages many of the latest features of ASP.NET development to
45: illustrate really simply building rich web applications with ASP.NET can be.
46: For more information about build web applications with ASP.NET please visit the
47: community web site at www.asp.net
48: </p>
49: </blockquote>
50: </td>
51: </tr>
52: </table>
53:
54: <h3>Spyworks Event Calendar</h3>
55: <table>
56: <tr class="rowH">
57: <th>Date</th>
58: <th>Title</th>
59: <th>Description</th>
60: </tr>
61: <tr class="rowA">
62: <td>June 01, 2011</td>
63: <td>Sed vestibulum blandit</td>
64: <td>
65: Come and check out demos of all the newest Tailspin Spyworks products and experience
66: them hands on.
67: </td>
68: </tr>
69: <tr class="rowB">
70: <td>November 28, 2011</td>
71: <td>Spyworks Product Demo</td>
72: <td>
73: Come and check out demos of all the newest Tailspin Spyworks products and experience
74: them hands on.
75: </td>
76: </tr>
77: <tr class="rowA">
78: <td>November 23, 2011</td>
79: <td>Spyworks Product Demo</td>
80: <td>
81: Come and check out demos of all the newest Tailspin Spyworks products and experience
82: them hands on.
83: </td>
84: </tr>
85: <tr class="rowB">
86: <td>November 21, 2011</td>
87: <td>Spyworks Product Demo</td>
88: <td>
89: Come and check out demos of all the newest Tailspin Spyworks products and experience
90: them hands on.
91: </td>
92: </tr>
93: </table>
Product Reviews
First we’ll add a button with a link to a form that we can use to enter a product review.
[!code-aspxMain]
1: <div class="SubContentHead">Reviews</div><br />
2: <a id="ReviewList_AddReview" href="ReviewAdd.aspx?productID=<%# Eval("ProductID") %>">
3: <img id="Img2" runat="server"
4: src="~/Styles/Images/review_this_product.gif" alt="" />
5: </a>
Note that we are passing the ProductID in the query string
Next let’s add page named ReviewAdd.aspx
This page will use the ASP.NET AJAX Control Toolkit. If you have not already done so you can download it from DevExpress and there is guidance on setting up the toolkit for use with Visual Studio here https://www.asp.net/learn/ajax-videos/video-76.aspx.
In design mode, drag controls and validators from the toolbox and build a form like the one below.
The markup will look something like this.
[!code-aspxMain]
1: <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
2: </asp:ToolkitScriptManager>
3: <div class="ContentHead">Add Review - <asp:label id="ModelName" runat="server" /></div>
4: <div>
5: <span class="NormalBold">Name</span><br />
6: <asp:TextBox id="Name" runat="server" Width="400px" /><br />
7: <asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator1"
8: ControlToValidate="Name"
9: Display="Dynamic"
10: CssClass="ValidationError"
11: ErrorMessage="'Name' must not be left blank." /><br />
12: <span class="NormalBold">Email</span><br />
13: <asp:TextBox id="Email" runat="server" Width="400px" /><br />
14: <asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator2"
15: ControlToValidate="Email" Display="Dynamic"
16: CssClass="ValidationError"
17: ErrorMessage="'Email' must not be left blank." />
18: <br /><hr /><br />
19: <span class="NormalBold">Rating</span><br /><br />
20: <asp:RadioButtonList ID="Rating" runat="server">
21: <asp:ListItem value="5" selected="True"
22: Text='<img src="Styles/Images/reviewrating5.gif" alt=""> (Five Stars) ' />
23: <asp:ListItem value="4" selected="True"
24: Text='<img src="Styles/Images/reviewrating4.gif" alt=""> (Four Stars) ' />
25: <asp:ListItem value="3" selected="True"
26: Text='<img src="Styles/Images/reviewrating3.gif" alt=""> (Three Stars) ' />
27: <asp:ListItem value="2" selected="True"
28: Text='<img src="Styles/Images/reviewrating2.gif" alt=""> (Two Stars) ' />
29: <asp:ListItem value="1" selected="True"
30: Text='<img src="Styles/Images/reviewrating1.gif" alt=""> (One Stars) ' />
31: </asp:RadioButtonList>
32: <br /><hr /><br />
33: <span class="NormalBold">Comments</span><br />
34: <cc1:Editor ID="UserComment" runat="server" />
35: <asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator3"
36: ControlToValidate="UserComment" Display="Dynamic"
37: CssClass="ValidationError"
38: ErrorMessage="Please enter your comment." /><br /><br />
39: <asp:ImageButton ImageURL="Styles/Images/submit.gif" runat="server"
40: id="ReviewAddBtn" onclick="ReviewAddBtn_Click" />
41: <br /><br /><br />
42: </div>
Now that we can enter reviews, lets display those reviews on the product page.
Add this markup to the ProductDetails.aspx page.
[!code-aspxMain]
1: <asp:ListView ID="ListView_Comments" runat="server"
2: DataKeyNames="ReviewID,ProductID,Rating" DataSourceID="EDS_CommentsList">
3: <ItemTemplate>
4: <tr>
5: <td><%# Eval("CustomerName") %></td>
6: <td>
7: <img src='Styles/Images/ReviewRating_d<%# Eval("Rating") %>.gif' alt="">
8: <br />
9: </td>
10: <td>
11: <%# Eval("Comments") %>
12: </td>
13: </tr>
14: </ItemTemplate>
15: <AlternatingItemTemplate>
16: <tr>
17: <td><%# Eval("CustomerName") %></td>
18: <td>
19: <img src='Styles/Images/ReviewRating_da<%# Eval("Rating") %>.gif' alt="">
20: <br />
21: </td>
22: <td><%# Eval("Comments") %></td>
23: </tr>
24: </AlternatingItemTemplate>
25: <EmptyDataTemplate>
26: <table runat="server">
27: <tr><td>There are no reviews yet for this product.</td></tr>
28: </table>
29: </EmptyDataTemplate>
30: <LayoutTemplate>
31: <table runat="server">
32: <tr runat="server">
33: <td runat="server">
34: <table ID="itemPlaceholderContainer" runat="server" border="1">
35: <tr runat="server">
36: <th runat="server">Customer</th>
37: <th runat="server">Rating</th>
38: <th runat="server">Comments</th>
39: </tr>
40: <tr ID="itemPlaceholder" runat="server"></tr>
41: </table>
42: </td>
43: </tr>
44: <tr runat="server">
45: <td runat="server">
46: <asp:DataPager ID="DataPager1" runat="server">
47: <Fields>
48: <asp:NextPreviousPagerField ButtonType="Button"
49: ShowFirstPageButton="True"
50: ShowLastPageButton="True" />
51: </Fields>
52: </asp:DataPager>
53: </td>
54: </tr>
55: </table>
56: </LayoutTemplate>
57: </asp:ListView>
58: <asp:EntityDataSource ID="EDS_CommentsList" runat="server" EnableFlattening="False"
59: AutoGenerateWhereClause="True"
60: EntityTypeFilter=""
61: Select="" Where=""
62: ConnectionString="name=CommerceEntities"
63: DefaultContainerName="CommerceEntities"
64: EntitySetName="Reviews">
65: <WhereParameters>
66: <asp:QueryStringParameter Name="ProductID" QueryStringField="productID"
67: Type="Int32" />
68: </WhereParameters>
69: </asp:EntityDataSource>
Running our application now and navigating to a product shows the product information including customer reviews.
Popular Items Control (Creating User Controls)
In order to increase sales on your web site we will add a couple of features to “suggestive sell” popular or related products.
The first of these features will be a list of the more popular product in our product catalog.
We will create a “User Control” to display the top selling items on the home page of our application. Since this will be a control, we can use it on any page by simply dragging and dropping the control in Visual Studio’s designer onto any page that we like.
In Visual Studio’s solutions explorer, right-click on the solution name and create a new directory named “Controls”. While it is not necessary to do so, we will help keep our project organized by creating all our user controls in the “Controls” directory.
Right-click on the controls folder and choose “New Item” :
Specify a name for our control of “PopularItems”. Note that the file extension for user controls is .ascx not .aspx.
Our Popular Items User control will be defined as follows.
[!code-aspxMain]
1: <%@ OutputCache Duration="3600" VaryByParam="None" %>
2: <div class="MostPopularHead">Our most popular items this week</div>
3: <div id="PanelPopularItems" runat="server">
4: <asp:Repeater ID="RepeaterItemsList" runat="server">
5: <HeaderTemplate></HeaderTemplate>
6: <ItemTemplate>
7: <a class='MostPopularItemText'
8: href='ProductDetails.aspx?productID=<%# Eval("ProductId") %>'>
9: <%# Eval("ModelName") %></a><br />
10: </ItemTemplate>
11: <FooterTemplate></FooterTemplate>
12: </asp:Repeater>
13: </div>
Here we’re using a method we have not used yet in this application. We’re using the repeater control and instead of using a data source control we’re binding the Repeater Control to the results of a LINQ to Entities query.
In the code behind of our control we do that as follows.
[!code-csharpMain]
1: using TailspinSpyworks.Data_Access;
2:
3: protected void Page_Load(object sender, EventArgs e)
4: {
5: using (CommerceEntities db = new CommerceEntities())
6: {
7: try
8: {
9: var query = (from ProductOrders in db.OrderDetails
10: join SelectedProducts in db.Products on ProductOrders.ProductID
11: equals SelectedProducts.ProductID
12: group ProductOrders by new
13: {
14: ProductId = SelectedProducts.ProductID,
15: ModelName = SelectedProducts.ModelName
16: } into grp
17: select new
18: {
19: ModelName = grp.Key.ModelName,
20: ProductId = grp.Key.ProductId,
21: Quantity = grp.Sum(o => o.Quantity)
22: } into orderdgrp where orderdgrp.Quantity > 0
23: orderby orderdgrp.Quantity descending select orderdgrp).Take(5);
24:
25: RepeaterItemsList.DataSource = query;
26: RepeaterItemsList.DataBind();
27: }
28: catch (Exception exp)
29: {
30: throw new Exception("ERROR: Unable to Load Popular Items - " +
31: exp.Message.ToString(), exp);
32: }
33: }
34: }
Note also this important line at the top of our control’s markup.
[!code-aspxMain]
1: <%@ OutputCache Duration="3600" VaryByParam="None" %>
Since the most popular items won’t be changing on a minute to minute basis we can add a aching directive to improve the performance of our application. This directive will cause the controls code to only be executed when the cached output of the control expires. Otherwise, the cached version of the control’s output will be used.
Now all we have to do is include our new control in our Default.aspc page.
Use drag and drop to place an instance of the control in the open column of our Default form.
Now when we run our application the home page displays the most popular items.
“Also Purchased” Control (User Controls with Parameters)
The second User Control that we’ll create will take suggestive selling to the next level by adding context specificity.
The logic to calculate the top “Also Purchased” items is non-trivial.
Our “Also Purchased” control will select the OrderDetails records (previously purchased) for the currently selected ProductID and grab the OrderIDs for each unique order that is found.
Then we will select al the products from all those Orders and sum the quantities purchased. We’ll sort the products by that quantity sum and display the top five items.
Given the complexity of this logic, we will implement this algorithm as a stored procedure.
The T-SQL for the stored procedure is as follows.
[!code-sqlMain]
1: ALTER PROCEDURE dbo.SelectPurchasedWithProducts
2: @ProductID int
3: AS
4: SELECT TOP 5
5: OrderDetails.ProductID,
6: Products.ModelName,
7: SUM(OrderDetails.Quantity) as TotalNum
8:
9: FROM
10: OrderDetails
11: INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
12:
13: WHERE OrderID IN
14: (
15: /* This inner query should retrieve all orders that have contained the productID */
16: SELECT DISTINCT OrderID
17: FROM OrderDetails
18: WHERE ProductID = @ProductID
19: )
20: AND OrderDetails.ProductID != @ProductID
21:
22: GROUP BY OrderDetails.ProductID, Products.ModelName
23:
24: ORDER BY TotalNum DESC
25: RETURN
Note that this stored procedure (SelectPurchasedWithProducts) existed in the database when we included it in our application and when we generated the Entity Data Model we specified that, in addition to the Tables and Views that we needed, the Entity Data Model should include this stored procedure.
To access the stored procedure from the Entity Data Model we need to import the function.
Double Click on the Entity Data Model in the Solutions Explorer to open it in the designer and open the Model Browser, then right-click in the designer and select “Add Function Import”.
Doing so will open this dialog.
Fill out the fields as you see above, selecting the “SelectPurchasedWithProducts” and use the procedure name for the name of our imported function.
Click “Ok”.
Having done this we can simply program against the stored procedure as we might any other item in the model.
So, in our “Controls” folder create a new user control named AlsoPurchased.ascx.
The markup for this control will look very familiar to the PopularItems control.
[!code-aspxMain]
1: <div>
2: <div class="MostPopularHead">
3: <asp:Label ID="LabelTitle" runat="server" Text=" Customers who bought this also bought:"></asp:Label></div>
4: <div id="PanelAlsoBoughtItems" runat="server">
5: <asp:Repeater ID="RepeaterItemsList" runat="server">
6: <HeaderTemplate></HeaderTemplate>
7: <ItemTemplate>
8: <a class='MostPopularItemText' href='ProductDetails.aspx?productID=<%# Eval("ProductId") %>'><%# Eval("ModelName") %></a><br />
9: </ItemTemplate>
10: <FooterTemplate></FooterTemplate>
11: </asp:Repeater>
12: </div>
13: </div>
The notable difference is that are not caching the output since the item’s to be rendered will differ by product.
The ProductId will be a “property” to the control.
[!code-csharpMain]
1: private int _ProductId;
2:
3: public int ProductId
4: {
5: get { return _ProductId ; }
6: set { _ProductId = Convert.ToInt32(value); }
7: }
In the control’s PreRender event handler we eed to do three things.
- Make sure the ProductID is set.
- See if there are any products that have been purchased with the current one.
- Output some items as determined in #2.
Note how easy it is to call the stored procedure through the model.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: protected void Page_PreRender(object sender, EventArgs e)
3: {
4: if (_ProductId < 1)
5: {
6: // This should never happen but we could expand the use of this control by reducing
7: // the dependency on the query string by selecting a few RANDOME products here.
8: Debug.Fail("ERROR : The Also Purchased Control Can not be used without
9: setting the ProductId.");
10: throw new Exception("ERROR : It is illegal to load the AlsoPurchased COntrol
11: without setting a ProductId.");
12: }
13:
14: int ProductCount = 0;
15: using (CommerceEntities db = new CommerceEntities())
16: {
17: try
18: {
19: var v = db.SelectPurchasedWithProducts(_ProductId);
20: ProductCount = v.Count();
21: }
22: catch (Exception exp)
23: {
24: throw new Exception("ERROR: Unable to Retrieve Also Purchased Items - " +
25: exp.Message.ToString(), exp);
26: }
27: }
28:
29: if (ProductCount > 0)
30: {
31: WriteAlsoPurchased(_ProductId);
32: }
33: else
34: {
35: WritePopularItems();
36: }
37: }
After determining that there ARE “also purchased” we can simply bind the repeater to the results returned by the query.
[!code-csharpMain]
1: //-------------------------------------------------------------------------------------+
2: private void WriteAlsoPurchased(int currentProduct)
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: var v = db.SelectPurchasedWithProducts(currentProduct);
9: RepeaterItemsList.DataSource = v;
10: RepeaterItemsList.DataBind();
11: }
12: catch (Exception exp)
13: {
14: throw new Exception("ERROR: Unable to Write Also Purchased - " +
15: exp.Message.ToString(), exp);
16: }
17: }
18: }
If there were not any “also purchased” items we’ll simply display other popular items from our catalog.
[!code-csharpMain]
1: //--------------------------------------------------------------------------------------+
2: private void WritePopularItems()
3: {
4: using (CommerceEntities db = new CommerceEntities())
5: {
6: try
7: {
8: var query = (from ProductOrders in db.OrderDetails
9: join SelectedProducts in db.Products on ProductOrders.ProductID
10: equals SelectedProducts.ProductID
11: group ProductOrders by new
12: {
13: ProductId = SelectedProducts.ProductID,
14: ModelName = SelectedProducts.ModelName
15: } into grp
16: select new
17: {
18: ModelName = grp.Key.ModelName,
19: ProductId = grp.Key.ProductId,
20: Quantity = grp.Sum(o => o.Quantity)
21: } into orderdgrp
22: where orderdgrp.Quantity > 0
23: orderby orderdgrp.Quantity descending
24: select orderdgrp).Take(5);
25:
26: LabelTitle.Text = "Other items you might be interested in: ";
27: RepeaterItemsList.DataSource = query;
28: RepeaterItemsList.DataBind();
29: }
30: catch (Exception exp)
31: {
32: throw new Exception("ERROR: Unable to Load Popular Items - " +
33: exp.Message.ToString(), exp);
34: }
35: }
36: }
To view the “Also Purchased” items, open the ProductDetails.aspx page and drag the AlsoPurchased control from the Solutions Explorer so that it appears in this position in the markup.
[!code-aspxMain]
1: <table border="0">
2: <tr>
3: <td>
4: <img src='Catalog/Images/<%# Eval("ProductImage") %>' border="0"
5: alt='<%# Eval("ModelName") %>' />
6: </td>
7: <td><%# Eval("Description") %><br /><br /><br />
8: <uc1:AlsoPurchased ID="AlsoPurchased1" runat="server" />
9: </td>
10: </tr>
11: </table>
Doing so will create a reference to the control at the top of the ProductDetails page.
[!code-aspxMain]
1: <%@ Register src="Controls/AlsoPurchased.ascx" tagname="AlsoPurchased" tagprefix="uc1" %>
Since the AlsoPurchased user control requires a ProductId number we will set the ProductID property of our control by using an Eval statement against the current data model item of the page.
When we build and run now and browse to a product we see the “Also Purchased” items.
|