ASP.NET MVC looping through session variable 'List' in the client

ChrisU 231 Reputation points
2023-02-17T10:00:20.0333333+00:00

I am setting up an ASP.NET MVC website and I am having a problem looping through a session variable in the client. The session variable is a List that I want to be a list of sites that will exist in a dropdown list in the navbar on all pages. So, this will exist within the _Layout.cshtml. At the moment I am setting the session variables with the HomeController.

I also posted this same question on Stackoverflow here, and whilst I learnt a bit, an answer as to how to loop through the session variable list in the client was not answered.

I used this stackoverflow post to get as far as I have done so far. However this post did not deal with displaying the list in the client.

The backend code is below.

Session Class:

namespace Customer_Application.Models
{
    public class UserSiteList
    {
        public string? Site { get; set; }
        public string? User { get; set; }
    }
}

SesssionExtensions class:

using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Text.Json;

namespace Customer_Application.DataLayer
{
    public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonSerializer.Serialize(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default : JsonSerializer.Deserialize<T>(value);
        }
    }
}

HomeController:

public IActionResult Index(int id)
{
    string sql = $"SELECT ID FROM [database].[dbo].[tblLogin] WHERE ID = {id}";
    string username = _SharedFunctions.String_Required(sql);

    contxt.HttpContext.Session.SetInt32("userID", id);
    contxt.HttpContext.Session.SetString("username", username);

    // Gets the site list for the user and adds to session
    userSiteList = new List<UserSiteList>
    {
        new UserSiteList { Site = "siteA", User = "dave.smith" },
        new UserSiteList { Site = "siteB", User = "dave.smith" }
    };
    contxt.HttpContext.Session.Set<List<UserSiteList>>("userSites", userSiteList);
    var value = HttpContext.Session.Get<List<UserSiteList>>("userSites");

    object Dashboard_inf = new Dashboard();

    return View(Dashboard_inf);
}

The value of 'value' is as expected:

User's image

And when returned using the code 'return Json(value)', the follow is returned to the client:

User's image

So I try to use this in the client:

_Layout.cshtml:

@inject IHttpContextAccessor contxt;

@{
    var userSites = contxt.HttpContext.Session.Get("userSites");
}
<!DOCTYPE html>
<html lang="en">
<head>
.
.
.
<ul class="navbar-nav flex-grow-1 pt-1">
    <li class="nav_item dropdown">
        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
            Sites
        </a>
        <ul class="dropdown-menu">
             @foreach (var item in userSites)
             {
                 <li>@item</li>
             }
        </ul>
    </li>
.
.

However this just produces a list of ascii character codes within the drop down list.

User's image

I think that this is something to do with how the 'userSites' variable is assigned in the _Layout.cshtml. I am pretty sure that '.Get' is incorrect, but do not know how to assign this otherwise.

Any help would be appreciated.

Developer technologies | ASP.NET | Other
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. AgaveJoe 30,491 Reputation points
    2023-02-17T11:53:21.02+00:00

    View components solve this type of programming problem where you have dynamic content in the layout.

    View components in ASP.NET Core

    Keep in mind, Session exists on the server. It is not possible for the client browser to access Session directly. If you want to continue with the current approach then you must serialize the list into JSON then render the JSON array within a script tags. Basically you're creating dynamic JavaScript/JSON. Then you'll write JavaScript to populate dynamic HTML from the JSON data.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.