好吧,像这样的问题有很多,我已经浏览了大约 1500 磅。我所看到的,人们要么发送了错误的类型,要么他们在做一些带有片面观点的事情。就我而言,我两者都没有做。所以,我的确切错误是:
传递到字典中的模型项的类型为“ClanSite.Models.ViewModels.CategoryViewModel”,但此字典需要类型为“ClanSite.Models.ViewModels.UserLoginViewModel”的模型项。
问题是我的 _Layout.cshtml (@model ClanSite.Models.ViewModels.UserLoginViewModel) 上有一个模型,用于在每个页面上登录用户。
但是,在其中一个页面上,我试图呈现一个类别列表。我的 CategoryViewModel 仅包含类别列表,GetCategories() 返回该列表。
Controller
public ActionResult Categories()
{
CategoryViewModel cats = new CategoryViewModel();
try
{
cats.Categories = ForumQueries.GetCategories();
}
catch
{
return RedirectToAction("Message", new { msg = "categories" });
}
return View(cats);
}
查看
@model ClanSite.Models.ViewModels.CategoryViewModel
@{
ViewBag.Title = "clanSite - Categories";
}
<div class="forumPostTable">
@foreach (ClanSite.Models.Tables.Join.Category cat in Model.Categories)
{
<div class="forumPostTableRow cursorPointer" onclick="linkTo('@Url.Action("Index", "Home")')">
<div class="forumCategoryTableCellTitle">
<div class="forumCategoryTitle">
<a href="" class="linkNoDecGold">Title</a>
</div>
<div class="forumCategoryTitleDesc">
@cat.CategoryInfo.Description
</div>
</div>
</div>
}
</div>
当我尝试访问此页面时,出现错误。我使用调试器单步执行该页面,并在以下位置获取正确的数据:@cat.CategoryInfo.Description
这真的让我很困惑,因为我能够使用该模型在另一个页面上创建用户注册表单,没有任何问题。那么,如何在 _Layout 和仅循环输出数据的 View 中使用模型?
最佳答案
我确实有一个 MVC 中的应用程序,它也需要很好地使用模型,而我的方法是不在 _Layout.cshtml
中使用模型。如果存在这种情况,例如登录操作,所有页面都需要,因此在 _Layout.cshtml
中定义,则应使用 RenderPartial
调用,并应使用特定的 Model也创建了。
<section id="login">
@{ Html.RenderPartial("_Login", new MyProjectName.Models.Account.LoginModel()); }
</section>
所有页面都将具有可用的部分 View 及其正确的模型。然后可以在 _Layout.cshtml
内的 RenderBody()
标记中创建并显示普通 View ,而不会出现任何模型冲突。
关于asp.net-mvc-3 - 传入字典的模型项是 A 类型,但该字典需要 B 类型的模型项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10924507/