Note that there are some explanatory texts on larger screens.

plurals
  1. POIn MVC 4 How do I Add multiple Collections to a session?
    primarykey
    data
    text
    <p>I'm using MVC 4 with Razor Syntax to create a collection based on a class that was created using scaffolding (Database first based development) and I can add the first collection to the Session and return it to the Index view and display it on the page. </p> <p>When I attempt to add a second collection to the Session Variable it gives me a error.</p> <pre><code> Unable to cast object of type 'System.Collections.Generic.List`1[EagleEye.Models.tblTask]' to type 'EagleEye.Models.tblTask'. </code></pre> <p>What am I doing wrong - how do I add 2 collections to the session?!</p> <p>Index.cshtml (My Index view using Razor syntax)</p> <pre><code>@model List&lt;myApp.Models.tblTask&gt; &lt;table&gt; @{ foreach (var tblTask in Model) { &lt;tr&gt; &lt;td&gt; TaskName: @tblTask.Name &lt;/td&gt; &lt;td&gt; Desc: @tblTask.Description &lt;/td&gt; &lt;td&gt; Schedule: @tblTask.Freq @tblTask.FreqUnit &lt;/td&gt; &lt;td&gt; Reocurring?: @tblTask.ReocurringTask.ToString() &lt;/td&gt; &lt;/tr&gt; } } &lt;/table&gt; </code></pre> <p>Here's the "ActionResult" portion of the code from my HomeController.cs:</p> <pre><code> [HttpPost] public ActionResult CreateTask(tblTask newTask) { var TaskCollection = new List&lt;tblTask&gt;(); if (Session["TaskCollection"] != null) { TaskCollection.Add((tblTask)Session["TaskCollection"]); } TaskCollection.Add(newTask); Session["TaskCollection"] = TaskCollection; return RedirectToAction("Index"); } public ActionResult Index() { var TaskCollection = new List&lt;tblTask&gt;(); if (Session["TaskCollection"] != null) { TaskCollection = (List&lt;tblTask&gt;)Session["TaskCollection"]; } return View(TaskCollection); } </code></pre> <p>When I add the first entry it works fine and shows up on my index view. When I try to add the second collection of tasks, it tells me:</p> <pre><code> Unable to cast object of type 'System.Collections.Generic.List`1[EagleEye.Models.tblTask]' to type 'EagleEye.Models.tblTask'. </code></pre> <p>I've been fighting this for a few days now and have been developing for a while, but am just beginning to learn the power of asking questions when I'm stumped (instead of just continuing to beat my head against the wall until something caves in (often my head), so if my question is not well formed, please let me know. </p> <p>Thanks! Dan</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload