Another simple ASP.NET MVC2 Question - ViewModels
This is the 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:
// 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 catego开发者_如何学运维ryName in Model.Categories)
{
%>
I think you could summarise my problem as an issue of iterating through a list in C#?
The error is as follows:
Cannot convert type 'AfvClassifieds.Models.Category' to 'string'
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:
<%: Html.DisplayFor(x => x.Categories) %>
and in ~/Views/YourControllerName/DisplayTemplates/Category.ascx
:
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AfvClassifieds.Models.Category>" %>
<div><%: Model.Name %></div>
精彩评论