Search code examples
entity-frameworkasp.net-mvc-3viewdata

Unpacking Multiple ViewData Results


So I want to display results from multiple queries from the same controller.

I have a controller method like this in mind:

public ActionResult Index() {
            string tmp_username = Membership.GetUser().ToString();
            ViewData["lemons"] = lemondb.lemon.Where(p => p.user == tmp_username).ToList();
            ViewData["sugar" ] = lemondb.sugar.Where( p => p.user == tmp_username ).ToList();
            return View();
}

And a view that resembles this:

    @foreach (var action in (List)ViewData["lemons"]) {
...
            @Html.DisplayFor( action.amount )
...
            @Html.DisplayFor( action.acidity )
    @foreach (var action in (List)ViewData["sugar"]) {
...
            @Html.DisplayFor( action.amount )
...
            @Html.DisplayFor( action.sweetness)

But I get an error on the 'foreach' lines that says something like:

CS0305: Using the generic type 'System.Collections.Generic.List' requires 1 type arguments

What argument am I missing?


Solution

  • I think this is a simple C# issue. You should cast the object from the ViewData to List<T>, where you have to replace T with the element type of your list. Check the type of the lemondb.lemon property to find out your element type.

    If the type is LemonTrader.Models.Message then try:

    @foreach (var action in (List<LemonTrader.Models.Message>)ViewData["lemons"])