[英]Another simple ASP.NET MVC2 Question - ViewModels
This is the ViewModel: 这是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; }
}
}
Let me explain this one, I want to capture everything from my Category table. 让我解释一下这一点,我想从我的类别表中捕获所有内容。 I then want to pass it to my view using a "strongly typed view".
然后,我想使用“强类型视图”将其传递给我的视图。 This I populate my new ViewModel:
我填充了新的ViewModel:
// Retrieve the categories table from the database.
var categoryModel = AfvClassifiedsDB.Categories.ToList();
// Set up our ViewModel
var viewModel = new ClassifiedsIndexViewModel()
{
Categories = categoryModel,
};
Then I want to iterate through my table in the view: (This is were its gone wrong). 然后,我想遍历视图中的表:( 这是错误的)。
<%
foreach (string categoryName in Model.Categories)
{
%>
I think you could summarise my problem as an issue of iterating through a list in C#? 我认为您可以将我的问题概括为一个遍历C#中的列表的问题?
The error is as follows: 错误如下:
Cannot convert type 'AfvClassifieds.Models.Category' to 'string'
无法将类型“ AfvClassifieds.Models.Category”转换为“字符串”
Ok so instead of: 好吧,而不是:
foreach (string categoryName in Model.Categories)
do: 做:
<% foreach (var category in Model.Categories) { %>
<div><%: category.Name %></div>
<% } %>
or: 要么:
<% foreach (Category category in Model.Categories) { %>
<div><%: category.Name %></div>
<% } %>
or even better: use display templates and never write a single foreach
in your view: 甚至更好:使用显示模板,并且永远不要在视图中编写单个
foreach
:
<%: Html.DisplayFor(x => x.Categories) %>
and in ~/Views/YourControllerName/DisplayTemplates/Category.ascx
: 并在
~/Views/YourControllerName/DisplayTemplates/Category.ascx
:
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AfvClassifieds.Models.Category>" %>
<div><%: Model.Name %></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.