2010-11-20 19 views
1

这是视图模型:另一种简单的ASP.NET MVC2的问题 - 的ViewModels

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using AfvClassifieds.Models; 

namespace AfvClassifieds.ViewModels 
{ 
    public class ClassifiedsIndexViewModel 
    { 
     public List<Category> Categories { get; set; } 
    } 
} 

让我解释一下这一块,我想捕捉一切从我的分类表。然后我想用“强类型视图”将它传递给我的视图。这是我填充我的新的ViewModel:

// Retrieve the categories table from the database. 
      var categoryModel = AfvClassifiedsDB.Categories.ToList(); 

      // Set up our ViewModel 
      var viewModel = new ClassifiedsIndexViewModel() 
      { 
       Categories = categoryModel, 
      }; 

然后,我想通过我的视点表迭代:(这是它出了问题)。

<% 
     foreach (string categoryName in Model.Categories) 
     { 
     %> 

我想你可以总结一下我的问题,通过在C#中的列表迭代的问题?

的错误如下:

无法将类型 'AfvClassifieds.Models.Category' 到 '字符串'

+0

出了什么事?我不明白你的问题。迭代的问题是什么?你想做什么?如果您要将数据库转储到其中,那看起来完全不像视图模型。 – 2010-11-20 20:54:09

+0

嘿Darin,增加了错误。 – JHarley1 2010-11-20 20:59:07

+0

究竟是什么字符串。在代码示例中停止使用变量。我们不是编译器。 – 2010-11-20 21:21:30

回答

3

好了,所以代替:

foreach (string categoryName in Model.Categories) 

做:

<% foreach (var category in Model.Categories) { %> 
    <div><%: category.Name %></div> 
<% } %> 

或:

<% foreach (Category category in Model.Categories) { %> 
    <div><%: category.Name %></div> 
<% } %> 

甚至更​​好:使用显示模板,从来不写在你的视图中的单个foreach

<%: Html.DisplayFor(x => x.Categories) %> 

~/Views/YourControllerName/DisplayTemplates/Category.ascx

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AfvClassifieds.Models.Category>" %> 
<div><%: Model.Name %></div> 
+0

你太快了 – 2010-11-20 21:02:14

+0

图例感谢达林! +++++++ – JHarley1 2010-11-20 21:03:09

+0

@ JHarley1,下一次包括您收到的错误消息。它让事情变得一目了然。如果这个答案对你有帮助,也不要忘记绿色的勾号。 – 2010-11-20 21:51:56