Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC Access ViewData Array?

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!

like image 436
Jacob Huggart Avatar asked Dec 03 '25 17:12

Jacob Huggart


1 Answers

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);
    })
%>
like image 129
Darin Dimitrov Avatar answered Dec 06 '25 20:12

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!