Search code examples
c#asp.net-mvcgeneric-collections

scoping issue in mvc view causing IList<t> to fail (was: how to instantiate list<t> in mvc view)


i have a Session var that has a List such that:

Session["roles"] = UserManager.GetRoles(uid) as List<string>;

that totally works
but now i want to use it in my layout such that:

@{
List<string> rolz = Session["roles"] as List<string>;
}@

and unfortunately i keep getting this err:
using the generic type "system.collections.generic.list" requires 1 type arguments

i see examples of passing lists over
but how do i use a preexisting session var that is already a list?

UPDATE 1:
pls note:
im interested in retrieving the Session["roles"] IN THE VIEW
not in another controller
as such the view is spitting up the error
because i do not think it likes this syntax "List"
because when im coding it it keeps trying to intellisense it like this:

List<string></string>

UPDATE 2: title has been adjusted to reflect the correct nature of this question


Solution

  • thank you to @tesuya for setting me in the right direction
    it seems that the real answer to this had nothing to do with pulling the Session values out
    but rather a scoping issue such that
    original full code looked like this:

    @{
         string me = @ViewContext.RouteData.Values["controller"].ToString() + "-" + @ViewContext.RouteData.Values["action"].ToString();
         string jscript = "/Scripts/es/" + me + ".js";
    }
    

    and then when i added the session var it failed such that:

    @{
        string me = @ViewContext.RouteData.Values["controller"].ToString() + "-" + @ViewContext.RouteData.Values["action"].ToString();
        string jscript = "/Scripts/es/" + me + ".js";
        var rolz = Session["roles"] as List<string>;
    }
    

    however everything worked when i did this:

    @{
        var rolz = Session["roles"] as List<string>;
        string me = @ViewContext.RouteData.Values["controller"].ToString() + "-" + @ViewContext.RouteData.Values["action"].ToString();
        string jscript = "/Scripts/es/" + me + ".js";
    }
    

    therefore the offending line caused problems was this:

        string me = @ViewContext.RouteData.Values["controller"].ToString() + "-" + @ViewContext.RouteData.Values["action"].ToString();
    

    which i still havent figgered out why
    but that is a question for another post...
    (above said in the tone of conan the barbarian)