ASP MVC访问ViewData数组?

Jac*_*art 2 asp.net-mvc viewdata

我有一些viewdata是通过我的存储库到数据库生成来获取一些调度信息.当信息存储在Viewdata中时,我注意到了viewdata的枚举.如何访问枚举项并根据viewdata生成表/列表?大多数信息只需要吐出到表中,但是一个项目将为其生成一个链接.

谢谢!

Dar*_*rov 7

当你说viewdata被枚举时,我不知道你真正明白你的意思.ViewData包含放在控制器操作中的对象实例.如果你放一个IEnumerable<T>你可以枚举的实例.因此,假设IEnumerable<ProductViewData>您从呈现视图的控制器操作中存储ViewData内部:

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();
}
Run Code Online (Sandbox Code Playgroud)

在视图中,您可以枚举并生成表:

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

那就是说,我建议你永远不要这样做,并且总是使用强类型视图.使用ViewData需要你在你的视图中强制转换和使用魔术字符串.

使用强类型视图时,这是相同的:

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" },
    });
}
Run Code Online (Sandbox Code Playgroud)

和观点:

<%@ 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>
Run Code Online (Sandbox Code Playgroud)

当您开始在MVCContrib中使用HTML帮助程序(例如Grid)时,事情变得更有希望:

<%= Html.Grid<ProductViewData>(Model)
    .Columns(column => {
        column.For(model => model.Id);
        column.For(model => model.Description);
    })
%>
Run Code Online (Sandbox Code Playgroud)