locked
Reading Cookies in _LoginPartial.cshtml RRS feed

  • Question

  • User1750806012 posted

    I am trying to make a shopping card dropdownlist where customers can see all the products on any page they go:

    @inject ApplicationDbContext _context
    
    @{
    
        var cookievalue = Request.Cookies["Shopping-card"]; // doesnt work either
    
        var userid = HttpContext.Request.Cookies["Shopping-card"];
        var ProductInShoppingcard = _context.shoppingCard.Where(x => x.ClientId == Guid.Parse(userid));
    }
    <ul class="navbar-nav">
        <div class="dropdown2">
            <button class="dropbutton">Shoppingcard @ViewBag.CountShoppingCard</button>
            <div class="dropdown-content">
                @foreach (var product in ProductInShoppingcard)
                {
                    <a href="">@product.ProductTitle | @product.Amount | @product.ProductPrice</a>
                }
             
            </div>
        </div>

    I am not able to get the value of the cookie wich is needed to link the right products with the richt customer
    I have tried to use Viewbag and pass the value from the controller to the _loginPartial but it can only return single data

    How can I reed Cookie value in _LoginPartial.cshtml?

    Thursday, April 22, 2021 2:27 PM

Answers

  • User475983607 posted

    I'm not sure what not working means.  The following code sample injects the IHttpContextAccessor to get to the cookies.

    @inject Microsoft.AspNetCore.Http.IHttpContextAccessor context
    @{
        ViewData["Title"] = "Index";
    
        var cookievalue = context.HttpContext.Request.Cookies["Shopping-card"];
    }
    
    <h1>Index</h1>
    
    <div>
        @cookievalue
    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 22, 2021 2:51 PM

All replies

  • User475983607 posted

    I'm not sure what not working means.  The following code sample injects the IHttpContextAccessor to get to the cookies.

    @inject Microsoft.AspNetCore.Http.IHttpContextAccessor context
    @{
        ViewData["Title"] = "Index";
    
        var cookievalue = context.HttpContext.Request.Cookies["Shopping-card"];
    }
    
    <h1>Index</h1>
    
    <div>
        @cookievalue
    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 22, 2021 2:51 PM
  • User1750806012 posted

    Thank you very much thats was what I was looking for

    Thursday, April 22, 2021 2:56 PM