Pobranie zmiennej z koszyka i wyliczenie kosztów

0

Witam.Prosze bardzo o pomoc
Robię koszyk na zakupy (tzn juz mam prawie kompletny) potrzebuje tylko aby wpisywana ilość sztuk danego produktu mnożona była przez wartośc za sztuke oraz żeby pokazywana była kwota całego zamówienia tak jak w załaczniku
(w tabeli pizza nastepujące kolumny, Id_pizzy,Nazwa_pizzy,Rozmiar_pizzy,Cena_pizzy)
Poniżej kod programu

  • plik Product.aspx
<%@ PAGE LANGUAGE="C#" AUTOEVENTWIREUP="true" CODEFILE="Product.aspx.cs" INHERITS="Product" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML XMLNS="http://www.w3.org/1999/xhtml">
<HEAD RUNAT="server">
    <TITLE>My Shopping Cart</TITLE>
</HEAD>
<BODY>
    
        <H2>My E-Commerce Shop</H2><br>
        TWOJE zamowienie<br>
        Pizza Rozmiar Ile Cena Akcja<br>
        <H2>
        My Shopping Cart</H2>
    <FORM ID="form2" >
      
        <BR />
        <TABLE BORDER="1" WIDTH="80%" CELLPADDING="0" CELLSPACING="0">
            <TR>
                <TD COLSPAN="2">
                    <ASP:LABEL ID="lblMsg" RUNAT="server"></ASP:LABEL>
                </TD>
            </TR>
            <ASP:REPEATER ID="rptShoppingCart" RUNAT="server">
                <HEADERTEMPLATE>
                </HEADERTEMPLATE>
                <ITEMTEMPLATE>
                    <TR>
                        <TD>
                            <%# DataBinder.Eval(Container.DataItem, "ProductID")%>
                            
                            
                        </TD>
                        <TD>
                        
                            
                            <%# DataBinder.Eval(Container.DataItem,"ProductName") %>
                        </TD>
                        <TD>
                            <A HREF="Product.aspx?action=remove&id=<%# DataBinder.Eval(Container.DataItem,"ProductID") %>">
                                usuń</A></TD>
                    </TR>
                </ITEMTEMPLATE>
                <FOOTERTEMPLATE>
                
                </FOOTERTEMPLATE>
            </ASP:REPEATER>
                </TABLE>
            <BR />
            Cena Zamówienia(suma wszystkich produktów)<br />
            <A HREF='Product.aspx'>Continue Shopping</A>
            <BR />
            <A HREF=''>Check Out </A>
    </FORM>
    <FORM ID="form1" RUNAT="server">
        CENA ZAMOWIENIA: 
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br>
       Miejscowosc <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br>
       Ulica <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br>
       Nr_domu <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br>
        Nr_telefonu <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox><br>
        Uwagi <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br>
        <asp:Button ID="Button1" runat="server" Text="Zamow" />
        <ASP:REPEATER ID="rptProducts" RUNAT="server" DataSourceID="SqlDataSource1">
            <HEADERTEMPLATE>
                <TABLE BORDER=1>
            </HEADERTEMPLATE>
            <ITEMTEMPLATE>
                <TR>
                    <TD>
                        <%#DataBinder.Eval(Container.DataItem, "Nazwa_pizzy")%>
                    </TD>
                    <TD>
                        <%#DataBinder.Eval(Container.DataItem, "Id_pizzy")%>
                    </TD>
                    <TD>
                        <%#DataBinder.Eval(Container.DataItem, "Rozmiar_pizzy")%>
                    </TD>
                    <TD>
                        <%#DataBinder.Eval(Container.DataItem, "Cena_pizzy")%>
                    </TD>
                      <TD>
                        <asp:TextBox runat="server"></asp:TextBox> 
                    </TD>
                    <TD><!--<a HREF='Product.aspx?action=add&ID=<%#DataBinder.Eval(Container.DataItem,"Id_pizzy") %>'>
                        Dodaj</a>-->
                       <!-- zle <asp:Button ID="Button2" runat="server" Text="Button" PostBackUrl='Product.aspx?action=add&ID=<%#DataBinder.Eval(Container.DataItem,"Id_pizzy") %>' />
                       --><script>
	$(function() {
		$( "input:submit, a, button", ".demo" ).button();
		$( "a", ".demo" ).click(function() { return false; });
	});
	</script>



<div class="demo">

<a href="Product.aspx?action=add&ID=<%#DataBinder.Eval(Container.DataItem,"Id_pizzy") %>" style="background-color: lightgrey; border-collapse: collapse; border-bottom: black 1px solid; border-left: black 1px solid; border-top: black 1px solid; border-right: black 1px solid; text-decoration: none;">Dodaj</a>

</div><!-- End demo -->



<div class="demo-description" style="display: none">
<p>Examples of the markup that can be used for buttons: A button element, an input of type submit and an anchor.</p>
</div><!-- End demo-description -->
                        </TD>
                    
                    
                </TR>
            </ITEMTEMPLATE>
            <FOOTERTEMPLATE>
                </table>
            </FOOTERTEMPLATE>
        </ASP:REPEATER>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT [Nazwa_pizzy], [Id_pizzy], [Rozmiar_pizzy], [Cena_pizzy] FROM [pizza]">
        </asp:SqlDataSource>
        <BR />
         <A HREF="ShoppingCart.aspx">My Shopping Cart</A>
        <BR />
        <A HREF="Checkout.aspx">CheckOut</A>
    </FORM>
</BODY>
</HTML>

  • plik Product.aspx.cs
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;
using System.Data.SqlClient;

public partial class Product : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            int iProductID = Convert.ToInt32(Request.QueryString["id"]);
            if (Request.QueryString["action"].Trim().ToLower() == "add")
            {
                AddToShoppingCart(iProductID);
            }
            else
            {
                RemoveShoppingCart(iProductID);
            }

        }

        if (!IsPostBack)
        {
            BindData();
        }
    }
    private void BindData()
    {
        if (Request.Cookies["ShoppingCart"] != null)
        {
            HttpCookie oCookie = (HttpCookie)Request.Cookies["ShoppingCart"];
            string sProductID = oCookie.Value.ToString();
            if (sProductID.Length == 0)
            {
                lblMsg.Text = "<B>No items in your shopping cart<B><BR>";
            }
            else
            {
                char[] sep = { ',' };
                string[] sArrProdID = sProductID.Split(sep);

                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("ProductID"));
                dt.Columns.Add(new DataColumn("ProductName"));
               // dt.Columns.Add(new DataColumn("Rozmiar_pizzy"));
               // dt.Columns.Add(new DataColumn("Cena_pizzy")); 
                dt.Columns.Add(new DataColumn("Counter"));

                int counter = 1;
                for (int i = 0; i < sArrProdID.Length; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["ProductID"] = sArrProdID[i];
                    dr["ProductName"] = GetProductName(sArrProdID[i]);
                    dr["Counter"] = counter;
                    dt.Rows.Add(dr);
                    counter++;
                }
                rptShoppingCart.DataSource = dt;
                rptShoppingCart.DataBind();
            }
        }
    }
    private string GetProductName(string ProductID)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        conn.Open();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = "select Nazwa_pizzy from pizza where Id_pizzy = '" + ProductID + "'";
        string ProductName = cmd.ExecuteScalar().ToString();
        conn.Close();
        return ProductName;
    }

    private void AddToShoppingCart(int ProductID)
    {
        if (Request.Cookies["ShoppingCart"] == null)
        {
            HttpCookie oCookie = new HttpCookie("ShoppingCart");
            //Set Cookie to expire in 3 hours
            oCookie.Expires = DateTime.Now.AddHours(3);
            oCookie.Value = ProductID.ToString();
            Response.Cookies.Add(oCookie);
        }
        else
        {
            bool bExists = false;
            char[] sep = { ',' };
            HttpCookie oCookie = (HttpCookie)Request.Cookies["ShoppingCart"];
            //Set Cookie to expire in 3 hours
            oCookie.Expires = DateTime.Now.AddHours(3);
            //Check if Cookie already contain same item
            string sProdID = oCookie.Value.ToString();

            string[] arrCookie = sProdID.Split(sep);

            for (int i = 0; i < arrCookie.Length; i++)
            {
                if (arrCookie[i].Trim() == ProductID.ToString().Trim())
                {
                    bExists = true;
                }
            }
            if (!bExists)
            {
                if (oCookie.Value.Length == 0)
                {
                    oCookie.Value = ProductID.ToString();
                }
                else
                {
                    oCookie.Value = oCookie.Value + "," + ProductID;
                }
            }

            //Add back into  the Response Objects.
            Response.Cookies.Add(oCookie);
        }
    }
    private void RemoveShoppingCart(int ProductID)
    {
        if (Request.Cookies["ShoppingCart"] == null)
        {
            //Do nothing
        }
        else
        {
            HttpCookie oCookie = (HttpCookie)Request.Cookies["ShoppingCart"];
            //Set Cookie to expire in 3 hours
            char[] sep = { ',' };
            oCookie.Expires = DateTime.Now.AddHours(3);
            //Check if Cookie already contain same item
            string sProdID = oCookie.Value.ToString();

            string[] arrCookie = sProdID.Split(sep);
            string[] arrCookie2 = new string[arrCookie.Length - 1];
            int j = 0;
            for (int i = 0; i < arrCookie.Length; i++)
            {
                if (arrCookie[i].Trim() != ProductID.ToString())
                {
                    arrCookie2[j] = arrCookie[i];
                    j++;
                }
            }
            string sCookieID = "";
            for (int i = 0; i < arrCookie2.Length; i++)
            {
                sCookieID = sCookieID + arrCookie2[i] + ",";
            }
            if (sCookieID.Length > 0)
            {
                oCookie.Value = sCookieID.Substring(0, sCookieID.Length - 1);
            }
            else
            {
                oCookie.Value = "";
            }



            //Add back into  the Response Objects.
            Response.Cookies.Add(oCookie);
        }
    }
}
0

A może w czym masz problem, bo mi nie chce się całego kodu analizować.

0

A mi się może i by chciało, ale nie mam na to czasu :P

0

Możesz zapisywać do cookie productID i jego ilość np. "productID1:1;productID2:33".
Nieznacznie modyfikując Twój kod:

private void AddToShoppingCart(int ProductID)
{
    if (Request.Cookies["ShoppingCart"] == null)
    {
        HttpCookie oCookie = new HttpCookie("ShoppingCart");
        //Set Cookie to expire in 3 hours
        oCookie.Expires = DateTime.Now.AddHours(3);
        oCookie.Value = ProductID.ToString() + ":1"; //#
        Response.Cookies.Add(oCookie);
    }
    else
    {
        bool bExists = false;
        char[] sep = { ',' };
        HttpCookie oCookie = (HttpCookie)Request.Cookies["ShoppingCart"];
        //Set Cookie to expire in 3 hours
        oCookie.Expires = DateTime.Now.AddHours(3);
        //Check if Cookie already contain same item
        string sProdID = oCookie.Value.ToString();

        string[] arrCookie = sProdID.Split(sep);
        string[] productParams;
        oCookie.Value = "";
        for (int i = 0; i < arrCookie.Length; i++)
        {
            string[] temp = arrCookie[i].Split(new char[]{':'});
            if (temp[0].Trim() == ProductID.ToString().Trim())
            {
                string[] productParams = temp;
                bExists = true;
            }
            else
            {
                oCookie.Value += arrCookie[i] + ",";
            }
        }
        if (!bExists)
        {
            if (oCookie.Value.Length == 0)
            {
                oCookie.Value = ProductID.ToString() + ":1";
            }
            else
            {
                oCookie.Value = oCookie.Value + ProductID + ":1";
            }
        }
        else
        {
            int count = Int32.Parse(productParams[1].Trim());
            ++count;
            oCookie.Value = oCookie.Value + productParams[0] + ":" + count.ToString();
        }


        //Add back into  the Response Objects.
        Response.Cookies.Add(oCookie);
    }
}

Reszta podobnie. Dobrze zrobisz jak wydzielisz sobie funkcje która będzie Ci parsowała tego string'a do jakiejś tablicy, bądź klasy/struktury i vice versa. Np. :

string[,] ProductsFromString(string productsString)
{
    if (productsString.Length == 0) return null;

    string[] splitedProducts = productsString.Split(new char[] { ',' });
    int productCount = splitedProducts.Length;
    string[,] products = new string[productCount, 2];

    for (int i = 0; i < productCount; ++i)
    {
        string[] splitedProduct = splitedProducts[i].Split(new char[] { ':' });
        products[i, 0] = splitedProduct[0];
        products[i, 1] = splitedProduct[1];
    }
    return products;
}

Pisane na 'sucho', mogą być błędy.

1 użytkowników online, w tym zalogowanych: 0, gości: 1