ASP.NET 电子商务与产品比较

分享于 

34分钟阅读

Web开发

  繁體

介绍

电子商务应用现在无处不在,许多人共享一组通用的功能。 在本文中,我将展示如何使用 GridViewListView 控件构建一个功能强大的产品页面。 我们将使用一些免费的剪贴画图片构建自行车商店产品网格。 示例文件是可以轻松添加到页面中的用户控件。 我们只使用了三个图像来保持样例应用程序的大小。

Product Grid

背景

本文假设读者使用 ObjectDataSource 控件对 GridViewListView 控件的数据绑定有些熟悉。

数据库

执行产品比较的产品页面至少需要三个表: 一个保存产品数据,二个支持产品比较功能。 在此示例中,产品图像存储在数据库中,并且使用图像处理程序来检索它们。 这些图像必须从应用程序中插入到数据库表中;不能从SQL控制台向表中添加图像。 这个示例项目包含一个控制台应用程序,它将在数据库中放置三个图像。 通常,至少有两个图像需要: 对于网格和比较页面,以及产品详细信息页面的较大图像。 表的其余部分将包含产品详细信息页所需的任何信息。

产品比较功能需要两个表: 一个可以保存唯一的键来区分会话,另一个用于保存与唯一键相关联的用户项。 域层代码使用 ADO.NET 调用存储过程以使用分页显示产品。 产品比较通过JavaScript处理,计算所选状态中的所有复选框,创建一个 cookie,用查询字符串调用。 比较页上的ObjectDataSource 具有" SelectMethod"属性,指向加载页时调用的方法。 ObjectDataSource.Select 方法调用存储过程来检索比较产品的信息,如果项计数超过了 ListViewGroupItemCount,则处理项的分页。 要运行该示例,首先执行数据库脚本" BicycleDatabase.sql",在 SQL Server的DatabaseImageInsert 项目的"数据库脚本"文件夹中找到。 然后将 DatabaseImageInsert 项目设置为启动项目并执行它。 这将把产品图像放在数据库中。

数据库映像应用程序

有很多示例显示如何从磁盘中选择图像并将它的存储在数据库中。 当图像直接从目录读取时,我找不到该方法的代码;换句话说,我无法读取图像处理程序。 从磁盘读取图像需要实例化 Bitmap 对象并读取到 MemoryStream 中。 从 Stream 中,得到一个字节 array,它被赋予 SqlCommand 对象。

产品网格

产品网格使用 GridView 和在用户控件中实现的ObjectDataSource。 我们必须在 SelectCountMethodSelectMethod的域类中实现两种方法。 网格将支持分页和排序,因此这些属性被设置为 true 我们将 DataKeyNames 设置为 ProductID的主键字段,并将 DataSourceID 设置为 ObjectDataSource的of。 img 元素由给定项的ProductID的图像处理程序填充。

<%@ControlLanguage="C#"AutoEventWireup="true"CodeBehind="ProductGrid.ascx.cs"Inherits="eCommerceProductGrid.UserControls.ProductGrid"%><%@Registerassembly="System.Web.Extensions, Version=3.5.0.0, 
 Culture=neutral, PublicKeyToken=31bf3856ad364e35"namespace="System.Web.UI.WebControls"tagprefix="asp"%><divstyle="float: left;"><asp:LabelID="PageResultsLabel"CssClass="resultPage"runat="server"Width="100%"EnableViewState="False"></asp:Label></div><br/><divstyle="padding-top: 5px; padding-bottom: 5px;"><asp:ButtonID="btnCompare"runat="server"CssClass="buttonStyle"Text="Compare Checked Items"Height="25"Width="190"EnableViewState="False"/><asp:LabelID="ComparisonError"runat="server"OnLoad="ComparisonError_Load"CssClass="errorMessage"EnableViewState="False"/><divstyle="float: right; margin-right: 20%; border: 1px solid black;"><asp:DropDownListID="GridPageNumberList"runat="server"Enabled="true"AutoPostBack="True"OnSelectedIndexChanged="GridPageNumberList_SelectedIndexChanged"><asp:ListItemValue="5">Display 5 per page</asp:ListItem><asp:ListItemValue="7">Display 7 per page</asp:ListItem></asp:DropDownList></div></div><asp:ObjectDataSourceID="SourceBicycles"runat="server"EnablePaging="True"SelectCountMethod="CountBicycles"SelectMethod="GetBicycleGridDetails"SortParameterName="SortExpression"TypeName="eCommereProductGrid.Domain.BicycleProductDB"></asp:ObjectDataSource><asp:GridViewID="gridBicycles"runat="server"AllowPaging="True"AllowSorting="True"AutoGenerateColumns="False"BackColor="White"CellPadding="0"DataKeyNames="ProductID"DataSourceID="SourceBicycles"EmptyDataText="No data returned from query"EnableViewState="false"Font-Names="Verdana"Font-Size="Small"GridLines="Horizontal"OnDataBound="GridBicycles_DataBound"OnPageIndexChanging="GridBicycles_PageIndexChanging"OnRowDataBound="GridBicycles_RowDataBound"PageSize="5"Width="80%"><FooterStyleBackColor="GhostWhite"BorderColor="Gainsboro"ForeColor="Blue"/><HeaderStyleBackColor="GhostWhite"BorderColor="Gainsboro"ForeColor="Blue"HorizontalAlign="Center"VerticalAlign="Middle"/><PagerSettingsPosition="TopAndBottom"FirstPageText="First"LastPageText="Last"Mode="NumericFirstLast"/><PagerStyleBackColor="GhostWhite"BorderColor="Gainsboro"ForeColor="Black"HorizontalAlign="Center"VerticalAlign="Middle"/><RowStyleBackColor="White"ForeColor="Black"/><Columns><asp:BoundFieldDataField="ProductID"/><asp:TemplateFieldItemStyle-HorizontalAlign="Center"ItemStyle-VerticalAlign="Middle"><ItemTemplate><inputtype="checkbox"id="checkBox"name="myCheckBox"runat="server"onclick=""value='<%# DataBinder.Eval(Container.DataItem, "ProductID") %>'/><br/><b>Compare</b></ItemTemplate><ItemStyleHorizontalAlign="Center"VerticalAlign="Middle"Width="65px"/></asp:TemplateField><asp:TemplateField><ItemTemplate><divstyle="padding-left: 15px; padding-right: 15px;"><ahref='<%# DataBinder.Eval(Container.DataItem, 
 "ProductGridLinkPage") %>?ProductID=
 <%# DataBinder.Eval(Container.DataItem, "ProductID") %>'><imgsrc='DatabaseImageHandler.ashx?ID=<%# Eval("ProductID") %>'alt='<%# DataBinder.Eval(Container.DataItem, "BrandName") %> 
 <%# DataBinder.Eval(Container.DataItem, "ModelName") %>'border="0"/></a></div></ItemTemplate></asp:TemplateField><asp:TemplateFieldHeaderText="Sort"SortExpression="LinkTitle"><ItemTemplate><table><tr><td><ahref='<%# DataBinder.Eval(Container.DataItem, 
 "ProductGridLinkPage") %>;?productID=<%# DataBinder.Eval(
 Container.DataItem, "ProductID") %>'><%# DataBinder.Eval(Container.DataItem, "LinkTitle")%></td></tr><tr><td><divid="summary"runat="server"><divid="expandedDiv"runat="server"style="display: none"><asp:LabelID="summaryExpanded"Runat="server"Text='<%# Eval("Summary") %>'></asp:Label></div><divid="collapsedDiv"runat="server"><asp:LabelID="summaryCollapsed"Runat="server"Text='<%# Eval("Summary") %>'></asp:Label></div><spanid="genericControl"runat="server"></span></div></td></tr><tr><td><asp:LabelID="standardCost"Runat="server"CssClass="gridStandardPrice"Text='<%# Eval("MSRP", "Price: {0:C}") %>'></asp:Label></td></tr><tr><td><asp:LabelID="listPrice"Runat="server"Text='<%# Eval("ListPrice", "MSRP: {0:C}") %>'></asp:Label></td></tr></table></ItemTemplate></asp:TemplateField></Columns></asp:GridView>

ProductGridPage_Load 事件调用了JavaScript函数 getCheckedBoxes(),它收集检查的CheckBox的in,并将它们存储在cookie中。 Compare按钮调用JavaScript函数 compareButtonClicked() 从cookie读取选中条目并使用由每个选中条目id组成的查询字符串调用 ProductComparison.aspx。 事件处理程序的GridViewRowDataBound 设置动态产品摘要文本 DIV s 以扩展和收缩。 通过将JavaScript方法分配给"比较"按钮并设置页面编号标签,GridViewDataBound 事件处理程序设置所有的内容进行产品比较。

using System;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using eCommereProductGrid.Domain;namespace eCommerceProductGrid.UserControls
{
 publicpartialclass ProductGrid : UserControl
 {
 #region Fieldsprivateconststring CHECKBOX_ATTRIBUTE = "ID";
 publicconststring CHECKBOX_STATE_SCRIPT = 
 "<script type='text/javascript'>getCheckedBoxes()</script>";
 publicconststring COMPARE_ITEMS_FUNCTION = "compareCheckedItems(this,'{0}')";
 publicconststring COMPARISON_RESULTS_TEXT = "Results {0} - {1} of {2}";
 privateconstint PRODUCT_SUMMARY_TEXT_WIDTH = 75;
 privateint pagingIndex;
 #endregion#region Event Handlersprotectedvoid Page_Load(object sender, EventArgs e)
 {
 ClientScriptManager csm = Page.ClientScript;
 if (!csm.IsStartupScriptRegistered(GetType(), "CheckBoxState"))
 {
 csm.RegisterStartupScript(GetType(), "CheckBoxState",
 CHECKBOX_STATE_SCRIPT);
 }
 }
 protectedvoid GridPageNumberList_SelectedIndexChanged(object sender, EventArgs e)
 {
 gridBicycles.PageSize = Convert.ToInt32(GridPageNumberList.SelectedValue);
 gridBicycles.DataBind();
 }
 protectedvoid ComparisonError_Load(object sender, EventArgs e)
 { // Get a reference to the Comparison Error Message Label// to issue error message if less than 2 items are checked ComparisonError = sender as Label;
 }
 protectedvoid GridBicycles_DataBound(object sender, EventArgs e)
 {
 foreach (GridViewRow row in gridBicycles.Rows)
 {
 // The ID column is necessary// for the comparisons checkbox. Remove it from view. row.Cells[0].Visible = false;
 }
 btnCompare.Attributes.Add("onclick", "compareButtonClicked();return false;");
 int maxRecords = GridRecordCount();
 int pageRecordCount = (pagingIndex + 1) * gridBicycles.PageSize;
 if (pageRecordCount > maxRecords)
 {
 pageRecordCount = maxRecords;
 }
 PageResultsLabel.Text = String.Format(COMPARISON_RESULTS_TEXT,
 pagingIndex * gridBicycles.PageSize + 1, pageRecordCount, maxRecords);
 }
 protectedvoid GridBicycles_PageIndexChanging(object sender,
 GridViewPageEventArgs e)
 {
 pagingIndex = e.NewPageIndex;
 }
 protectedvoid GridBicycles_RowDataBound(object sender, GridViewRowEventArgs e)
 {
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
 TableCell cell = e.Row.Cells[2];
 Label summaryExpanded = (Label)cell.FindControl("summaryExpanded");
 HtmlGenericControl theCollapsedDiv = 
 (HtmlGenericControl)cell.FindControl("collapsedDiv");
 HtmlGenericControl theExpandedDiv = 
 (HtmlGenericControl)cell.FindControl("expandedDiv");
 string scriptCollapse =
 "( <span class="caretback">«</span><" + 
 "script language="""javascript" type="text/javascript">" +
 "if(document.getElementById){document.writeln('<a" + 
 "href="javascript:void(0)" onclick="return" +
 " toggleDisplay(' +"'" + theCollapsedDiv.ClientID + 
 "'" + ')"> less</a>');}</script>)";
 string summaryExpandedText = summaryExpanded.Text;
 summaryExpanded.Text = summaryExpandedText + scriptCollapse;
 Label summaryCollapsed = (Label)cell.FindControl("summaryCollapsed");
 string originalText = summaryCollapsed.Text;
 if (originalText.Length > PRODUCT_SUMMARY_TEXT_WIDTH)
 {
 String text = originalText.Substring(
 PRODUCT_SUMMARY_TEXT_WIDTH - 1, 15);
 int indexOfFirstBlank = text.IndexOf(' ');
 if (indexOfFirstBlank!= -1)
 {
 string truncatedText = originalText.Substring(0, 
 PRODUCT_SUMMARY_TEXT_WIDTH + indexOfFirstBlank - 1);
 string scriptExpand = "( <span class="caret" + 
 "back">»</span><script language="""javascript"" +
 "type="text/javascript">if(document" + 
 ".getElementById){document.writeln('<a" +
 " href="javascript:void(0)" onclick="return" + 
 "toggleDisplay(' +"'" +
 theExpandedDiv.ClientID + "'" + 
 ')"> more</a>');}</script>)";
 summaryCollapsed.Text = truncatedText + "..." + scriptExpand;
 }
 }
 HtmlGenericControl regGeneric = 
 (HtmlGenericControl)cell.FindControl("genericControl");
 regGeneric.InnerHtml = 
 "<script language="""javascript" type" + 
 "="text/javascript">registerToggle('" +
 theCollapsedDiv.ClientID + "', '" + 
 theExpandedDiv.ClientID.ToString() + "');</script>";
 // Add product ID to the row's checkBox so it can be uniquely identified HtmlInputCheckBox cb = (HtmlInputCheckBox)cell.FindControl("checkBox");
 eCommereProductGrid.Domain.BicycleProduct gp = 
 (e.Row.DataItem as eCommereProductGrid.Domain.BicycleProduct);
 cb.Attributes.Add(CHECKBOX_ATTRIBUTE, gp.ProductID.ToString());
 cb.Attributes.Add("onclick", 
 String.Format(COMPARE_ITEMS_FUNCTION, gp.ProductID));
 }
 }
 #endregion#region Properties#endregion#region Private Methodsprivateint GridRecordCount()
 {
 return BicycleProductDB.CountBicycles();
 }
 #endregion }
}

当单击"比较项"按钮时,调用函数 compareButtonClicked(),创建一个保存选中状态 CheckBox的cookie。

function createCookie(name, value, days)
{
 if (days) {
 var date = new Date();
 date.setTime(date.getTime()+(days*24*60*60*1000));
 var expires = "; expires="+date.toGMTString();
 }
 else {
 var expires = "";
 }
 document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name)
{
 var nameFormatted = name+"=";
 var cookies = document.cookie.split(';');
 for(var i=0; i < cookies.length; i++) {
 var cookie = cookies[i];
 while (cookie.charAt(0) == ' ')
 cookie = cookie.substring(1, cookie.length);
 if (cookie.indexOf(nameFormatted) == 0)
 return cookie.substring(nameFormatted.length, cookie.length);
 }
 returnnull;
}
function compareCheckedItems(checkBox, itemno)
{
 var compareCookie = getCookie('compareCookie');
 var comparedItems = new Array();
 if (checkBox.checked == true) {
 if (compareCookie) {
 comparedItems = compareCookie.split(',');
 comparedItems.unshift(itemno);
 if (comparedItems.length >12) {
 comparedItems.pop();
 }
 compareCookie = comparedItems.join(',');
 createCookie('compareCookie', compareCookie, 0);
 }
 else {
 createCookie('compareCookie', itemno, 0);
 }
 }
 elseif (checkBox.checked == false) {
 comparedItems = compareCookie.split(',');
 for(var i = 0; i <= comparedItems.length-1; i++) 
 {
 if (comparedItems[i] == itemno) {
 comparedItems.splice(i,1);
 compareCookie = comparedItems.join(',');
 createCookie('compareCookie', compareCookie, 0);
 }
 }
 }
}
function compareButtonClicked()
{
 var compareCookie = getCookie('compareCookie');
 var isValidSelection = false;
 if (compareCookie) {
 var comparedItems = new Array();
 comparedItems = compareCookie.split(',');
 if (comparedItems.length >1) {
 isValidSelection = true;
 }
 }
 if (isValidSelection) {
 var queryString = "";
 for (var i = 0; i < comparedItems.length; i++) {
 var item = "ID=" + comparedItems[i];
 if (i!= comparedItems.length - 1)
 queryString = queryString + item + "&";
 else queryString = queryString + item;
 }
 if (document.domain == "localhost")
 window.location.href = 'http://localhost:49625/ComparePage.aspx?' + 
 queryString;
 else window.location.href = 'http://' + document.domain + 
 '/ComparePage.aspx?' + queryString;
 }
 else {
 alert('Please select at least two items to compare.');
 }
}
function makeNewCookie() {
 var compareCookie = "";
 createCookie('compareCookie', compareCookie, 0);
}
function getCheckedBoxes() {
 var mc = getCookie('compareCookie');
 if (mc) {
 var checkedItems = new Array();
 checkedItems = mc.split(',');
 var checkBoxes = new Array();
 checkBoxes = document.getElementsByTagName('input');
 for (var i = 0; i <= checkedItems.length-1; i++) {
 for (var x = 0; x <= checkBoxes.length-1; x++) {
 if (checkedItems[i] == checkBoxes[x].value) {
 checkBoxes[x].checked = true;
 }
 }
 }
 }
}

下面是网格的ObjectDataSource的域类。 类 BicycleProduct 只是一个具有重载构造函数和自动的public 属性的类,为了简洁起见,这里省略了。

using System.ComponentModel;using System.Data;using System.Data.SqlClient;using System.Web.Configuration;using System.Collections.Generic;namespace eCommereProductGrid.Domain
{
 publicclass BicycleProductDB
 {
 publicstaticint CountBicycles()
 {
 int nRows;
 using (SqlConnection connection = 
 new SqlConnection(WebConfigurationManager.
 ConnectionStrings["BicycleDatabase"].ConnectionString))
 {
 SqlCommand command = connection.CreateCommand();
 command.Connection = connection;
 command.CommandType = CommandType.StoredProcedure;
 command.CommandText = "CountBicycleProducts";
 connection.Open();
 nRows = (int)command.ExecuteScalar();
 }
 return nRows;
 }
 [DataObjectMethod(DataObjectMethodType.Select, false)]
 public List<BicycleProduct> GetBicycleGridDetails(
 string SortExpression, int startRowIndex, int maximumRows)
 {
 List<BicycleProduct> list = new List<BicycleProduct>();
 DataSet dataSet = new DataSet();
 using (SqlConnection connection = 
 new SqlConnection(WebConfigurationManager.
 ConnectionStrings["BicycleDatabase"].ConnectionString))
 {
 using (SqlCommand command = connection.CreateCommand())
 {
 command.CommandType = CommandType.StoredProcedure;
 command.CommandText = "GetAllProductsPaged";
 command.Parameters.Add(new SqlParameter("@Start", SqlDbType.Int, 4));
 command.Parameters["@Start"].Value = startRowIndex;
 command.Parameters.Add(new SqlParameter("@Count", SqlDbType.Int, 4));
 command.Parameters["@Count"].Value = maximumRows;
 SqlDataAdapter adapter = new SqlDataAdapter(command);
 connection.Open();
 adapter.Fill(dataSet, "Bicycles");
 }
 }
 DataView view = dataSet.Tables[0].DefaultView;
 view.Sort = SortExpression;
 foreach (DataRowView row in view)
 {
 BicycleProduct displayDetails = new BicycleProduct(
 (string) row["BrandName"],
 (string)row["Color"],
 (string)row["GridPageImageName"],
 (string)row["LinkTitle"],
 (decimal)row["ListPrice"],
 (string)row["ModelName"],
 (decimal)row["MSRP"],
 (int)row["PercentSaved"],
 (int)row["ProductID"],
 (string)row["ProductPageImageName"],
 (string)row["ProductGridLinkPage"],
 (decimal)row["Savings"],
 (string)row["Summary"],
 (decimal)row["Weight"]);
 list.Add(displayDetails);
 }
 return list;
 }
 publicstaticvoid GetProductDetailsFor(int ProductID, DataSet displaySet)
 {
 using (SqlConnection connection = 
 new SqlConnection(WebConfigurationManager.
 ConnectionStrings["BicycleDatabase"].ConnectionString))
 {
 SqlCommand command = connection.CreateCommand();
 command.CommandType = CommandType.StoredProcedure;
 command.CommandText = "GetProductDetailsByProductID";
 command.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.Int, 4));
 command.Parameters["@ProductID"].Value = ProductID;
 SqlDataAdapter adapter = new SqlDataAdapter(command);
 connection.Open();
 adapter.Fill(displaySet, "ProductDetails");
 }
 }
 }
}

Our类接收要显示的项的ID,从数据库检索它,并将它的提供给 GridView

using System;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.IO;using System.Web;namespace eCommerceProductGrid
{
 publicclass DatabaseImageHandler : IHttpHandler
 {
 publicvoid ProcessRequest(HttpContext context)
 {
 if (context.Request.QueryString["ID"] == null)
 thrownew ArgumentException("No parameter specified");
 using (SqlConnection connection = 
 new SqlConnection(ConfigurationManager.
 ConnectionStrings["BicycleDatabase"].ConnectionString))
 {
 string sql = "SELECT GridPageImage," + 
 "ImageContentType FROM BicycleProduct WHERE ProductID=@ID";
 SqlCommand sqlCommand = new SqlCommand(sql, connection);
 sqlCommand.CommandType = CommandType.Text;
 sqlCommand.Parameters.Add("@ID", SqlDbType.Int, 4);
 sqlCommand.Parameters["@ID"].Value = context.Request.QueryString["ID"];
 connection.Open();
 SqlDataReader reader = sqlCommand.ExecuteReader(CommandBehavior.Default);
 reader.Read();
 try {
 MemoryStream stream = new MemoryStream((
 byte[])reader["GridPageImage"]);
 byte[] buffer = new byte[stream.Length];
 int byteSeq = stream.Read(buffer, 0, (int)stream.Length);
 context.Response.ContentType = reader["ImageContentType"].ToString();
 while (byteSeq >0)
 {
 context.Response.OutputStream.Write(buffer, 0, byteSeq);
 byteSeq = stream.Read(buffer, 0, (int)stream.Length);
 }
 }
 catch (SqlException ex)
 {
 context.Response.Write(ex.Message);
 }
 finally {
 reader.Close();
 }
 }
 }
 publicbool IsReusable
 {
 get {
 returnfalse;
 }
 }
 }
}

产品比较页面

比较页使用与 GridView 相同的ListViewObjectDataSource,但没有 SortParameterName 属性。 ListView 设置为每页显示4 项,并启用分页。

ComparisonGrid

<%@ControlLanguage="C#"AutoEventWireup="true"CodeBehind="ProductComparison.ascx.cs"Inherits="eCommerceProductGrid.UserControls.ProductComparison"%><asp:ObjectDataSourceID="sourceBicycles"runat="server"EnablePaging="True"SelectCountMethod="CountBicycles"SelectMethod="CompareBicycleDetails"TypeName="eCommereProductGrid.Domain.CompareBicycleProductsDB"><SelectParameters><asp:QueryStringParameterName="QueryValues"QueryStringField="ID"/></SelectParameters></asp:ObjectDataSource><asp:ListViewID="ListView"Runat="server"DataSourceID="sourceBicycles"GroupItemCount="4"><LayoutTemplate><tableid="LayoutTable"runat="server"border="1"><trid="groupPlaceholder"runat="server"></tr></table><asp:DataPagerrunat="server"ID="ContactsDataPager"PageSize="4"><Fields><asp:TemplatePagerField><PagerTemplate><divclass="productComparisonPager"><b> Page
 <asp:Labelrunat="server"ID="CurrentPageLabel"Font-Size="Small"Text="<%# Container.TotalRowCount>0? 
 (Container.StartRowIndex/Container.PageSize) + 1 : 0%>"/> of
 <asp:Labelrunat="server"ID="TotalPagesLabel"Font-Size="Small"Text="<%# Math.Ceiling ((double)Container.TotalRowCount/
 Container.PageSize) %>"/><br/></b></div></PagerTemplate></asp:TemplatePagerField><asp:NumericPagerFieldPreviousPageText=" <Prev 4"NextPageText="Next 4>"/></Fields></asp:DataPager></LayoutTemplate><GroupTemplate><tr><tdrunat="server"id="itemPlaceholder"valign="top"/></tr></GroupTemplate><ItemTemplate><td><tableclass="comparisonTable"id="rptProduct"runat="server"border="0"><tr><tdstyle="height: 50px;font-size: small"><ahref='<%# DataBinder.Eval(Container.DataItem, 
 "ProductGridLinkPage") %>?productID=<%# DataBinder.Eval(
 Container.DataItem, "ProductID") %>'/><%# DataBinder.Eval(Container.DataItem, "LinkTitle")%></td></tr><tr><tdstyle="height: 50px;"><ahref='<%# DataBinder.Eval(Container.DataItem, 
 "ProductGridLinkPage") %>?ProductID=<%# DataBinder.Eval(
 Container.DataItem, "ProductID") %>'/><imgsrc='DatabaseImageHandler.ashx?ID=<%# DataBinder.Eval(
 Container.DataItem, "ProductID") %>'alt="<%# DataBinder.Eval(Container.DataItem, 
 "BrandName") %><%# DataBinder.Eval(Container.DataItem, 
 "ModelName") %>"border="0"/></td></tr><tr><td><b>Brand:</b><%# DataBinder.Eval(Container.DataItem, "BrandName")%></td></tr><tr><td><b>Model:</b><%# DataBinder.Eval(Container.DataItem, "ModelName")%></td></tr><tr><td><b>Color:</b><%# DataBinder.Eval(Container.DataItem, "Color")%></td></tr><tr><td><b>Weight:</b><%# DataBinder.Eval(Container.DataItem, "Weight")%></td></tr><trclass="comparisonPrice"><td><b>List Price:</b> 
 <%# DataBinder.Eval(Container.DataItem, "ListPrice", "{0:C}")%></td></tr><tr><td><b>MSRP:</b><%# DataBinder.Eval(Container.DataItem, "MSRP", "{0:C}")%></td></tr><tr><td><b>Savings:</b><%# DataBinder.Eval(Container.DataItem, "Savings", "{0:C}")%> (<%# DataBinder.Eval(Container.DataItem, "PercentSaved")%>%)</td></tr><tr><tdstyle="height: 35px"align="center"><asp:ButtonID="RemoveItemButton"runat="server"CommandName="REMOVE"CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProductID") %>'oncommand="ImageButton_Command"Text="Remove"/></td></tr><tr><tdstyle="height: 35px"align="center"><asp:ButtonID="DisplayItemButton1"runat="server"CommandName="DISPLAY"CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProductID") %>'Text="Display"oncommand="ImageButton_Command"/></td></tr></tr></table></td></ItemTemplate></asp:ListView>

代码中的Page_Load 事件处理程序解析和存储查询字符串中的,如果比较中有两个以上的项。 按钮单击处理程序只执行给定的命令,或者删除某个项或者显示项目的产品页。

using System;using System.Collections.Generic;using System.Collections.Specialized;using System.Text;using System.Web.UI.WebControls;using System.Web.UI;using eCommereProductGrid.Domain;namespace eCommerceProductGrid.UserControls
{
 publicpartialclass ProductComparison : UserControl
 {
 #region Fieldsprivateconststring DISPLAY_ITEM = "DISPLAY";
 privateconststring REMOVE_ITEM = "REMOVE";
 private List<int> queryArgs = new List<int>();
 #endregion#region Event Handlersprotectedvoid Page_Load(object sender, EventArgs e)
 {
 NameValueCollection coll = Request.QueryString;
 String[] key = coll.AllKeys;
 for (int loop1 = 0; loop1 < key.Length; loop1++)
 {
 String[] value = coll.GetValues(key[loop1]);
 if (value!= null && value.Length >0)
 {
 for (int ix = 0; ix <value.Length; ix++)
 {
 int id = Convert.ToInt32(Server.HtmlEncode(value[ix]));
 queryArgs.Add(id);
 }
 }
 }
 }
 protectedvoid ImageButton_Command(object sender, CommandEventArgs e)
 {
 if (e.CommandName == DISPLAY_ITEM)
 {
 int productID = Convert.ToInt32(e.CommandArgument);
 string pageName = CompareBicycleProductsDB.GetProductPageName(productID);
 Response.Redirect("~/" + pageName + "?ProductID=" + productID, true);
 }
 elseif (e.CommandName == REMOVE_ITEM)
 {
 if (ListView.Items.Count >2)
 {
 queryArgs.Remove(Convert.ToInt32((string)e.CommandArgument));
 Response.Redirect("~/ComparePage.aspx?" + ParseQueryArgs());
 }
 }
 }
 #endregion#region Private Methods 
 privatestring ParseQueryArgs()
 {
 StringBuilder query = new StringBuilder();
 foreach (int parm in queryArgs)
 {
 if (query.Length!= 0)
 {
 query.Append("&");
 }
 query.AppendFormat("ID={0}", parm);
 }
 return query.ToString();
 }
 #endregion }
}

运行示例代码

示例代码是一个 Visual Studio 2008解决方案,并使用 SQL Server 2008. 在 localhost 下执行解决方案时,localhost使用的端口号必须与执行比较页面的JavaScript函数 compareButtonClicked() 中的端口号相同。 我将端口 49625添加为解决方案的属性,但是你的计算机可能需要另一个端口。 在,将网络项目的属性更改为你的端口号,并更改 ProductComparison.js的第 92行,以包含新端口号。

  • 生成解决方案
  • DatabaseImageInsert 项目设置为启动项目
  • 在 SQL Server 中的数据库脚本文件夹中执行SQL脚本
  • 执行 DatabaseImageInsert 项目
  • eCommerceProductGrid 设置为启动项目并运行它

COM  COMM  asp  asp-net  GRID  Gridview  
相关文章