所以我将以下视图模型传递给我的视图,但是每当我尝试访问该页面时视图都会抛出异常。关于为什么会发生这种情况的任何解释都会很棒,关于如何修复它的指针会更好!感谢。
The model item passed into the dictionary is of type
MyCompareBase.Models.CategoryIndex', but this dictionary requires a model item
of type
'System.Collections.Generic.IEnumerable`1[MyCompareBase.Models.CategoryIndex]'.
查看模型
public class CategoryIndex
{
public string Title { get; set; }
[DisplayName("Categories")]
public IEnumerable<string> CategoryNames { get; set; }
}
查看
@model IEnumerable<MyCompareBase.Models.CategoryIndex>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryNames)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
控制器
public ActionResult Index()
{
var localDb = db.Categories.Select(c => c.Name);
var wcf = category.Categories().Select(c => c.Name);
var all = new HashSet<String>(localDb);
all.UnionWith(wcf);
var viewModel = new Models.CategoryIndex
{
Title = "Avaliable Product Categories",
CategoryNames = all.AsEnumerable()
};
return View(viewModel);
}
答案 0 :(得分:4)
您要发送单个CategoryIndex
对象进行查看,但您的视图需要IEnumerable<CategoryIndex>.
答案 1 :(得分:0)
Valin是正确的,您需要传递IEnumerable。您可以将代码修改为:
public ActionResult Index()
{
var localDb = new List<string>{"a", "b"};
var wcf = new List<string>{"b","c"};
var all = new HashSet<String>(localDb);
all.UnionWith(wcf);
var viewModel = new List<CategoryIndex>
{
new CategoryIndex
{
Title = "Avaliable Product Categories",
CategoryNames = all.AsEnumerable()
}
};
return View(viewModel);
}