这是ViewModel:
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'类型转换为'string'
答案 0 :(得分: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>