Search code examples
c#asp.netlinqwebmatrix

How do I cast a ASP.NET session to get back my list?


Background: I have two web pages, one is a list of things, and the other is the detail of the thing. On the list, the user can filter and sort, which results in a sorted list. On the details, I would like the user to have Next and Previous navigation.

I'm using ASP.Net Web Pages with Razor, edited with either WebMatrix or Visual Studio. The code on the list page is simple. The RefID is an integer Key uniquely identify the record:

var db = Database.Open("dbname");
...
var q = db.Query( sqlthatworks , passInVarables);
Session["WorkingList"] = q.Select( x => new { x.RefID } );

On the details page, I need to be able to access the Session["WorkingList"] such that I can use the Linq provided by this StackOverFLow question to find the next and previous records, which will be something like:

var workingList = (IEnumerable<dynamic>) Session["WorkingList"];
var nextRecord = workingList.SkipWhile(i => i.RefID != currentRecord).Skip(1).First();

I know that db.Query returns a IEnumerable< Object>, but I'm guessing what's really coming back is a IEnumerable< dynamic >. And that works, but seems overly complicated. Is there a better way?


Solution

  • You're much better off creating a class for the RefID value. This will allow you to do this:

    public class RefContainer {
        // maybe RefID is not an int...?
        public Int32 RefID { get; set; }
    }
    
    Session["WorkingList"] = q.Select(x => new RefContainer { RefID = x.RefID });
    
    var workingList = Session["WorkingList"] as IEnumerable<RefContainer>;
    if (workingList != null) {
        var nextRecord = workingList
            .SkipWhile(i => i.RefID != currentRecord)
            .Skip(1).First();
    }