According to various sources online i should use this
public static class SessionExtensions
{
/// <summary>
/// Get value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <param name="key"></param>
/// <returns></returns>
public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key)
{
return (T)session[key];
}
/// <summary>
/// Set value.
/// </summary>
/// <param name="session"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetDataToSession(this HttpSessionStateBase session, string key, object value)
{
session[key] = value;
}
}
To make use of session objects in mvc. I have made the following BaseController
public class BaseController : Controller
{
public int UserID
{
get { return Session.GetDataFromSession<int>("UserID"); }
set { Session.SetDataToSession("UserID", value); }
}
}
I now inherit the BaseController
public class RequestsController : BaseController
{
private FooModel db = new FooModel ();
// GET: Requests
public ActionResult Index()
{
var viewModel = Mapper.RequestIndex(UserID);
return View(viewModel);
}
}
And i can use the UserID session object without issue.
How do i use that same session object on my view, without adding it to the model.
<div class="clearfix">
@if (Session["UserID"].ToString() == "1")
{
<div class="btn btn-default pull-right ">
@Html.ActionLink("Super Special link for User 1", "sslfu1")
</div>
}
</div>
The Session["UserID"]
is incorrect here. What should i use?
I have modified my
SessionExtensions
class to include the following:Then on the view reference it like this:
@Session.GetDataFromSession("UserID")
It's not strongly typed , but this fits more naturaly