I am working on rendering a set of cart items using a user control. Each cart item can be removed via a button in the user control. When a cart item is removed I need to visually show it's removal. However, since the cart item existed during the loading of the page it remains until the page is refreshed again. What I am after is a means to refresh the page after the work to remove the cartitem has been completed.
The code behind cart.aspx.cs looks like:
protected void Page_Init(object sender, EventArgs e)
{
CreateCartItemControls();
}
private void CreateCartItemControls()
{
foreach (CartItem ci in Profile.Cart.Items)
{
ASP.CartItemControl cic = new ASP.CartItemControl();
cic.ItemName = ci.Name;
cic.CartID = ci.ID;
cic.Cost = ci.BaseCost.ToString("c");
cic.ItemComponents = ci.Components;
cic.CartItemRemoved += new EventHandler(CartItemRemoved);
Content.Controls.Add(cic);
}
}
void CartItemRemoved(object sender, EventArgs e)
{
Master.UpdateCartItemCount();
}
Markup for CartItemControl.ascx
<%@ Control Language="C#" ClassName="CartItemControl" AutoEventWireup="true"
CodeFile="CartItemControl.ascx.cs"
Inherits="UserControls_CartItemControl" %>
<fieldset id="FieldSet" runat="server">
<legend>
<asp:HyperLink ID="ItemLink" runat="server" />
</legend>
<asp:ImageButton ID="RemoveCartItem" AlternateText="Remove Item"
ImageUrl="~/img/buttons/remove_4c.gif" runat="server"
CommandName="Remove" OnCommand="RemoveCartItem_Command" />
<asp:Label ID="TotalItemCost" runat="server" Text="$0.00" />
<ol>
<li runat="server" id="ComponentsLI" visible="false">
<fieldset id="ComponentsFieldSet" runat="server">
<legend>Item Components</legend>
<asp:CheckBoxList ID="ItemComponentsCheckList"
runat="server" />
</fieldset>
</li>
</ol>
</fieldset>
Code behind for the UserControl CartItemControl.ascx.cs
public partial class UserControls_CartItemControl
: System.Web.UI.UserControl
{
public string ItemName { get; set; }
public int CartID { get; set; }
public string Cost { get; set; }
public IDictionary<int, SoftwareComponent> ItemComponents { get; set; }
protected void Page_PreRender(object sender, EventArgs e)
{
SetCartItemControlAttributes();
}
private void SetCartItemControlAttributes()
{
ItemLink.Text = ItemName;
TotalItemCost.Text = Cost;
RemoveCartItem.CommandArgument = CartID.ToString();
if (!ItemComponents.Count.Equals(0))
{
ComponentsLI.Visible = true;
foreach (KeyValuePair<int, ItemComponent> kvp in
ItemComponents)
{
ItemComponentsCheckList.Items.Add(
new ListItem(string.Format("{0} {1}",
kvp.Value.ComponentName,
kvp.Value.ComponentCost.ToString("c")),
kvp.Key.ToString()));
}
}
}
public event EventHandler CartItemRemoved;
protected void RemoveCartItem_Command(object sender, CommandEventArgs e)
{
int itemID;
if (int.TryParse(e.CommandArgument.ToString(), out itemID))
{
Profile.Cart.RemoveCartItem(itemID);
CartItemRemoved(sender, e);
Parent.Controls.Remove(this);
}
}
}