Home > Net >  Is there a way to pass session object to a method?
Is there a way to pass session object to a method?

Time:12-06

I am still newbie and learning about session, I want to pass the session CartItem to OrderLine's consturctor so I can use it to save data in database like this but how?

    SaveOrderLine(Cartitem caritem) {
int id = cartitem.getID
int Price =cartitem.Price 
etc etc. 

execute.query }

this is CartItem which will be used as session to hold items that a customer choose`enter code here

public class CartItem
        {
                public long ProductId { get; set; }
                public string ProductName { get; set; }
                public int Quantity { get; set; }
                public double Price { get; set; }
                public double Total
                {
                        get { return Quantity * Price; }
                }
                public string Image { get; set; }

                public CartItem()
                {
                }

                public CartItem(Product product)
                {
                        ProductId = product.ID;
                        ProductName = product.Name;
                        Price = product.Price;
                        Quantity = 1;
                       
                }

        }

And this is the controller for CartItem

public IActionResult Index()
{
    List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart") ?? new List<CartItem>();

    CartViewModel cartVM = new()
    {
        CartItems = cart,
        GrandTotal = cart.Sum(x => x.Quantity * x.Price)
    };

    return View(cartVM);
}

public async Task<IActionResult> Add(int id)
{

    //Consume API
    Product product = new Product();
   
    connectToAPI.UseUrl  = "api/products/"   id;
    //Check response
    HttpResponseMessage getData = await connectToAPI.CallServiceGet();

    if (getData.IsSuccessStatusCode)
    {

        string results = getData.Content.ReadAsStringAsync().Result;
        product = JsonConvert.DeserializeObject<Product>(results);
    }

    else
    {
        Console.WriteLine("Error");
    }

    // Product product = await _context.Product.FindAsync(id);

    List<CartItem> cart = HttpContext.Session.GetJson<List<CartItem>>("Cart") ?? new List<CartItem>();

    CartItem cartItem = cart.Where(c => c.ProductId == id).FirstOrDefault();

    if (cartItem == null)
    {
        cart.Add(new CartItem(product));
    }
    else
    {
        cartItem.Quantity  = 1;
    }

    HttpContext.Session.SetJson("Cart", cart);

    TempData["Success"] = "The product has been added!";

    return Redirect(Request.Headers["Referer"].ToString());
}

And This is Cart View

    @model CartViewModel

@{
    ViewData["Title"] = "Cart Overview";
}

@if (Model.CartItems.Count > 0)
{
    <table >
        <tr>
            <th>Product</th>
            <th>Quantity</th>
            <th></th>
            <th>Price</th>
            <th>Sub Total</th>
        </tr>
        @foreach (var item in Model.CartItems)
        {
            <tr>
                <td>@item.ProductName</td>
                <td>@item.Quantity</td>
                <td>
                    <a  asp-action="Add" asp-route-id="@item.ProductId"> </a>
                    <a  asp-action="Decrease" asp-route-id="@item.ProductId">-</a>
                    <a  asp-action="Remove" asp-route-id="@item.ProductId">Remove</a>
                </td>
                <td>@item.Price kr.</td>
                <td>@Model.CartItems.Where(x => x.ProductId == item.ProductId).Sum(x => x.Quantity * x.Price) kr.</td>
            </tr>
        }
        <tr>
            <td  colspan="4"> Total: @Model.GrandTotal kr.</td>
        </tr>
        <tr>
            <td  colspan="4">
                <a  asp-action="Clear">Clear Cart</a>
                <a  href="#">Checkout</a>
            </td>
        </tr>
    </table>


}
else
{
    <h3 >Your cart is empty.</h3>
}

And this is OrderLine where I want to pass session CartItem object to it but I don't know how

 public class OrderLine
{

  
    public int ProductID { get; set; }
 
    public int OrderID { get; set; }
    public int Quantity { get; set; }
    public double TotalPrice { get; set; }

    List<Product> products1= new List<Product>();


    public OrderLine(int productID, int orderID, int saleQuantity, double totalPrice)
    {
        this.ProductID = productID;
        this.OrderID = orderID;
        this.Quantity = saleQuantity;
        this.TotalPrice = totalPrice;

    }

CodePudding user response:

Firstly,since you want to pass int type productID and orderID to OrderLine constructor,you should have the int type properties in CartItem:

public class CartItem
    {
        public int ProductId { get; set; }
        public int OrderId { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public double Price { get; set; }
        public double Total
        {
            get { return Quantity * Price; }
        }
        public string Image { get; set; }

        public CartItem()
        {
        }

        public CartItem(Product product)
        {
            ProductId = product.ID;
            ProductName = product.Name;
            Price = product.Price;
            Quantity = 1;

        }

    }
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }

After using the models above,here is a demo to pass CartItem in session to OrderLine:

 HttpContext.Session.SetString("CartItem", JsonConvert.SerializeObject(new CartItem { ProductId = 1 ,OrderId=11, Price=1, Quantity=2}))
 CartItem c = JsonConvert.DeserializeObject<CartItem>(HttpContext.Session.GetString("CartItem"));
 OrderLine o = new OrderLine(c.ProductId, c.OrderId, c.Quantity, c.Total);

result:

enter image description here

  • Related