web层的控件之四-----ShoppingCartControl

先把这个控件的试图截下来吧:

这样看来这个控件的职责一目了然了吧。

protectedvoid Page_PreRender(object sender, EventArgs e) {
if (!IsPostBack) {
BindCart();
}
}

上面用了页面生命周期的preRender意在页面呈现之前对控件Repeater绑定一些购物车的数据。故调用了BindCart函数,接下来就看这个函数是怎么绑定数据的吧:

privatevoid BindCart() {

ICollection
<CartItemInfo> cart = Profile.ShoppingCart.CartItems;
if (cart.Count >0) {
repShoppingCart.DataSource
= cart;
repShoppingCart.DataBind();
PrintTotal();
plhTotal.Visible
=true;
}
else {
repShoppingCart.Visible
=false;
plhTotal.Visible
=false;
lblMsg.Text
="Your cart is empty.";
}

}

先用一个ICollection泛值类型加载Cart对象,如果这个对象有值就把数据绑定在Repeater控件。接下来还调用了PrintTotal函数,那么看下这个函数吧:

privatevoid PrintTotal() {
if (Profile.ShoppingCart.CartItems.Count >0)
ltlTotal.Text
= Profile.ShoppingCart.Total.ToString("c");
}

通过调用BLL.Cart的Total属性得到购物车购买相应宠物的总价格(数量*单价)。

 

计算总价格。

 1 protectedvoid BtnTotal_Click(object sender, System.Web.UI.ImageClickEventArgs e) {
2 TextBox txtQuantity;
3 ImageButton btnDelete;
4 int qty =0;
5 foreach (RepeaterItem row in repShoppingCart.Items) {
6 txtQuantity = (TextBox)row.FindControl("txtQuantity");//从空间Repeater空间中的TextBox得到购买数量
7 btnDelete = (ImageButton)row.FindControl("btnDelete");//获得删除按钮
8 if (int.TryParse(WebUtility.InputText(txtQuantity.Text, 10), out qty)) { //限定数量的长度要小于10位
9 if (qty >0)//如果有数量
10 Profile.ShoppingCart.SetQuantity(btnDelete.CommandArgument, qty);
11 elseif (qty ==0)
12 Profile.ShoppingCart.Remove(btnDelete.CommandArgument);
13 }
14
15 }
16 Profile.Save();
17 BindCart();
18 }

最重要的还是要看下这个代码行数10的调用BLL.Cart的SetQuantity函数啦。这个函数很简单:

publicvoid SetQuantity(string itemId, int qty) {
cartItems[itemId].Quantity
= qty;
}

这个函数要求第一个参数是宠物的编号itemId。那么怎么样才能得到这个itemId呢?这就要看ImageButton这个控件做了些什么了:

<asp:ImageButton ID="btnDelete" runat="server" BorderStyle="None" CausesValidation="false"
CommandArgument
='<%# Eval("ItemId") %>' CommandName="Del" ImageUrl="~/Comm_Images/button-delete.gif"
OnCommand="CartItem_Command" ToolTip="Delete" />

这个ImageButton的CommandArgument就绑定了宠物的ItemId。这样就可以啦。。

 

接下啦还有一个ImageButton事件:

protectedvoid CartItem_Command(object sender, CommandEventArgs e) {
switch (e.CommandName.ToString()) {
case"Del":
Profile.ShoppingCart.Remove(e.CommandArgument.ToString());
break;
case"Move":
Profile.ShoppingCart.Remove(e.CommandArgument.ToString());
Profile.WishList.Add(e.CommandArgument.ToString());
break;
}
Profile.Save();
BindCart();
}

算了,这个事件我就不加说明了。没什么可说的了。

 

下面有段张逸老师说的,用控件,且直接处理控件的业务逻辑的好处(我觉得很不错):

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2011-07-19 21:45  小霖2012  阅读(279)  评论(0编辑  收藏  举报