views:

143

answers:

1

I have some viewdata that is generated by going through my repository to the database to grab some scheduling info. When the information is stored in the Viewdata, I noticed that the viewdata is enumerated. How could I access the enumerated items and generate a table/list based on the viewdata? Most of the information just needs to be spit out into a table, but one item will have a link generated for it.

Thanks!

+2  A: 

I don't know really understand what you mean when you say that the viewdata is enumerated. The ViewData contains instances of objects that you put inside your controller action. If you put an instance of an IEnumerable<T> you could enumerate. So let's suppose that you store an IEnumerable<ProductViewData> inside your ViewData from the controller action that's rendering the view:

public ActionResult Index()
{
    ViewData["products"] = new[]
    {
        new ProductViewData { Id = 1, Description = "product 1" },
        new ProductViewData { Id = 2, Description = "product 2" },
        new ProductViewData { Id = 3, Description = "product 3" },
    }
    return View();
}

Inside the view you could enumerate and generate a table:

<table>
<% foreach (ProductViewData product in (IEnumerable<ProductViewData>)ViewData["products"]) { %>
<tr>
  <td><%= product.Id %></td>
  <td><%= Html.Encode(product.Description) %></td>
</tr>
<% } %>
</table>

That being said you, I would recommend you to never do this and always use strongly typed views. Using ViewData requires you to cast and use magic strings inside your views which IMHO is bad.

Here's the same using a strongly typed view:

public ActionResult Index()
{
    return View(new[]
    {
        new ProductViewData { Id = 1, Description = "product 1" },
        new ProductViewData { Id = 2, Description = "product 2" },
        new ProductViewData { Id = 3, Description = "product 3" },
    });
}

and the view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SomeNamespace.ProductViewData>" %>

<table>
<% foreach (var product in Model) { %>
<tr>
  <td><%= product.Id %></td>
  <td><%= Html.Encode(product.Description) %></td>
</tr>
<% } %>
</table>

and things get even more promising when you start using HTML helpers in MVCContrib such as the Grid:

<%= Html.Grid<ProductViewData>(Model)
    .Columns(column => {
        column.For(model => model.Id);
        column.For(model => model.Description);
    })
%>
Darin Dimitrov
A strongly-typed view definitely sounds better. But I am not sure how to display a list of data from my model that is only after a certain date.
Jacob Huggart
Make the controller or the model do the filtering of the view model.
Darin Dimitrov