Implementation of ASP.NET MVC Shopping Cart

Asked

Viewed 4,974 times

1

I am trying to set up a "simple" selling system, but I have no knowledge in e-commerce. What I want is the following:

The user chooses the products he wants, assembles a cart, and finalizes the order. There begins my question: the cart is half done, I can add the items and the desired amount, but I do not know how to calculate to display the total value.

Follows my Action:

public ActionResult AdicionarCarrinho(int id)
        {
            List<ItemDesign> carrinho = Session["Carrinho"] != null ? (List<ItemDesign>)Session["Carrinho"] : new List<ItemDesign>();

            Design d = db.Design.Find(id);

            if (d != null)
            {
                ItemDesign i = new ItemDesign();
                i.Design = d;
                i.Qtd = 1;
                i.IdDesign = d.IdDesign;

                if (carrinho.Where(x => x.IdDesign == d.IdDesign).FirstOrDefault() != null)
                {
                    carrinho.Where(x => x.IdDesign == d.IdDesign).FirstOrDefault().Qtd += 1;
                }

                else
                {
                    carrinho.Add(i);


                }
                Session["Carrinho"] = carrinho;

            }

            return RedirectToAction("Carrinho");

        }



public ActionResult Carrinho()
    {
        List<ItemDesign> carrinho = Session["Carrinho"] != null ? (List<ItemDesign>)Session["Carrinho"] : new List<ItemDesign>();

        return View(carrinho);
    }

My first question is: How can I calculate the total value according to the items in the cart?

Second question: What to do after I finished the cart? What I was trying to do was more or less the following:

The user finalizes the order, and opens a payment screen (billet only). He would type in his data (name and Cpf, I don’t know) and the system would generate a "pseudo-billet" with the buyer’s data and the items he requested. It doesn’t have to be a real ticket, because I don’t intend to implement it.

Follow my tables:

Design:
IdDesign
Servico
Preco

ItemDesign:
Id
IdDesign
IdPedido

Pedido:
IdPedido
DtPedido
StatusPedido
IdUsuario
DtPagamento
ValorTotal

I accept suggestion of any tutorial/book on E-commerce.

Edit: View trolley

@model List<AllFiction.Models.ItemDesign>     


@{
    ViewBag.Title = "Carrinho";
}

<h2>Carrinho</h2>


    @foreach (var item in Model)

    {

    <li>
        @item.IdDesign - @item.Design.Servico

        <input type="text" value="@item.Qtd" readonly="readonly"/>
        <input type="submit" value="alterar" />
        @Html.ActionLink("Remover", "Remover", "Shop", new {id=item.IdDesign}, null)
    </li>   


    }
@Html.ActionLink("Retornar", "Servicos", "Shop")
  • Do you want to do this calculation on View or in Controller?

  • I think in the controller. I intend to save this value later in the database, or no difference?

  • In this case, it is better in the Controller even.

1 answer

2


I’m guessing your Models be it so:

public class Design 
{
    [Key]
    public int DesignId { get; set; }
    public String Servico { get; set; }
    public Decimal Preco { get; set; }

    public virtual ICollection<ItemDesign> ItensDesign { get; set; }
}

public class ItemDesign 
{
    [Key]
    public int ItemDesignId { get; set; }
    public int DesignId { get; set; }
    public int PedidoId { get; set; }

    public virtual Design Design { get; set; }
    public virtual Pedido Pedido { get; set; }
}

public class Pedido 
{
    [Key]
    public int PedidoId { get; set; }
    public int UsuarioId { get; set; }
    public DateTime DtPedido { get; set; }
    public StatusPedido StatusPedido { get; set; } // StatusPedido seria um Enum

    public DateTime DtPagamento { get; set; }
    public Decimal ValorTotal { get; set; }

    public virtual Usuario Usuario { get; set; }
    public virtual ICollection<ItemDesign> ItensDesign { get; set; }
}

It’s not very secret. You’ve done everything right so far. I’m just going to change a few things to make the calculation easier:

    public ActionResult AdicionarCarrinho(int id)
    {
        // Ao invés de colocar uma lista de ítens de Design, vamos colocar
        // Um objeto da entidade Pedido, que já possui List<ItemDesign>.
        // List<ItemDesign> carrinho = Session["Carrinho"] != null ? (List<ItemDesign>)Session["Carrinho"] : new List<ItemDesign>();
        Pedido carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

        var design = db.Design.Find(id);

        if (design != null)
        {
            var itemDesign = new ItemDesign();
            itemDesign.Design = design;
            itemDesign.Qtd = 1;
            // Esta linha não precisa. O EF é espertinho e preenche pra você.
            // itemDesign.IdDesign = design.IdDesign;

            if (carrinho.ItensDesign.FirstOrDefault(x => x.IdDesign == design.IdDesign) != null)
            {
                carrinho.ItensDesign.FirstOrDefault(x => x.IdDesign == design.IdDesign).Qtd += 1;
            }

            else
            {
                carrinho.ItensDesign.Add(itemDesign);
            }

            // Aqui podemos fazer o cálculo do valor

            carrinho.ValorTotal = carrinho.ItensDesign.Select(i => i.Design).Sum(d => d.Preco);

            Session["Carrinho"] = carrinho;
        }

        return RedirectToAction("Carrinho");
    }

    public ActionResult Carrinho()
    {
        Pedido carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

        return View(carrinho);
    }

To View would look like this:

@model Pedido

@{
    ViewBag.Title = "Carrinho";
}

<h2>Carrinho</h2>

    @foreach (var item in Model.ItensDesign)
    {
        <li>
            @item.IdDesign - @item.Design.Servico

            <input type="text" value="@item.Qtd" readonly="readonly"/>
            <input type="submit" value="alterar" />
            @Html.ActionLink("Remover", "Remover", "Shop", new {id=item.IdDesign}, null)
        </li>
    }

@Html.ActionLink("Retornar", "Servicos", "Shop")
  • I’m having a little trouble assembling the cart view now. As I was using the Itemdesign model, I had a list with the product name and quantity. I will edit it for you to see...

  • You can access the same attributes as my old view using the requested model?

  • 1

    @Ryansantos I edited the answer.

  • Shit, it’s becoming a routine now! Once again, thank you.

  • Just takes away a doubt. What would you indicate to resolve the issue of payment? I mean, I don’t think I can go around generating bank slips at will (or can!?). I just need to simulate an e-commerce anyway..

  • Use a Gateway, like Pagseguro.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.