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 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:
And when returned using the code 'return Json(value)', the follow is returned to the client:
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.
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.