将模型传递给视图
Posted
技术标签:
【中文标题】将模型传递给视图【英文标题】:Passing Model to View 【发布时间】:2013-12-16 17:52:35 【问题描述】:所以我将以下视图模型传递给我的视图,但每次我尝试访问该页面时,视图都会引发异常。关于为什么会发生这种情况的任何解释都会很好,关于如何解决它的指针会更好!谢谢。
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);
【问题讨论】:
【参考方案1】:您正在发送单个 CategoryIndex
对象来查看,但您的视图需要 IEnumerable<CategoryIndex>.
【讨论】:
感谢您的帮助,对 .Net 还很陌生,但我已经解决了。【参考方案2】: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);
【讨论】:
以上是关于将模型传递给视图的主要内容,如果未能解决你的问题,请参考以下文章