在我的控制器里我有:
Category x = new Category(1, "one", 0);
Category y = new Category(2, "two", 1);
Category z = new Category(3, "three", 1);
List<Category> categories = new List<Category>();
categories.Add(x);
categories.Add(y);
categories.Add(z);
ViewData["categories"] = categories;在我看来:
<%= Html.DropDownList("categories")%>但我有个错误:
具有键“ViewData”类型的ViewData项是“System.Collections.Generic.List`1[System.Collections.Generic.List`1,MvcApplication1,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]”,但必须是“IEnumerable”类型。
如何解决这个问题?
发布于 2012-04-08 17:25:49
你也许可以试试
ViewData["categories"] = new SelectList(categories, "Id", "Name");(假设类别有一个名称和Id字段)
然后可以将逻辑添加到键控选定的值中。
编辑:因为您的错误消息不完整,如果我没有错的话:它要求的是一个IEnumerable<SelectListItem>
发布于 2012-04-08 17:31:01
在创建ViewData项之前的行中,可以将List<T>转换为IEnumerable<T>
IEnumerable<Category> cat = categories;
ViewData["categories"] = cat;发布于 2012-04-08 18:24:45
更好的方法是为每个视图/页面创建一个视图模型,用数据填充它(如果需要的话)并将其返回到视图/页。不要将域模型返回到视图/页。
下面提供的代码用于ASP.NET MVC3,但很容易与您的情况相关联。
让我们假设您正在创建一个需要在一个类别中(显示在选择列表中)的新产品,所以您需要一个Create视图/页面和操作方法。我将创建以下视图模型:
public class ProductCreateViewModel
{
// Include other properties if needed, these are just for demo purposes
public string Name { get; set; }
public string SKU { get; set; }
public string LongDescription { get; set; }
// This is the unique identifier of your category,
// i.e. foreign key in your product table
public int CategoryId { get; set; }
// This is a list of all your categories populated from your category table
public IEnumerable<Category> Categories { get; set; }
}类别类别:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}在Create视图中,您将拥有以下内容:
@model MyProject.ViewModels.ProductCreateViewModel
@using (Html.BeginForm())
{
<table>
<tr>
<td><b>Category:</b></td>
<td>
@Html.DropDownListFor(x => x.CategoryId,
new SelectList(Model.Categories, "Id", "Name", Model.CategoryId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
</td>
</tr>
</table>
<!-- Add other HTML controls if required and your submit button -->
}您的创建操作方法:
public ActionResult Create()
{
ProductCreateViewModel viewModel = new ProductCreateViewModel
{
// Here you do a database call to populate your dropdown
Categories = categoryService.GetAllCategories()
};
return View(viewModel);
}https://stackoverflow.com/questions/10064732
复制相似问题