gpt4 book ai didi

asp.net-mvc-3 - 传入字典的模型项是类型 A,但此字典需要类型 B 的模型项

转载 作者:行者123 更新时间:2023-12-04 05:44:00 25 4
gpt4 key购买 nike

好的,有很多这样的问题,我已经浏览了大约 1500 磅。我看到的那些,人们要么发送错误的类型,要么他们正在做一些带有局部 View 的事情。在我的情况下,我都不做。所以,我的确切错误是:

传递到字典中的模型项的类型为“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应该使用调用并且还应该创建一个特定的模型。

<section id="login">
@{ Html.RenderPartial("_Login", new MyProjectName.Models.Account.LoginModel()); }
</section>

所有页面都将具有可用的部分 View 及其适当的模型。然后可以在 RenderBody() 中创建和显示普通 View 。标签内 _Layout.cshtml没有任何模型冲突。

关于asp.net-mvc-3 - 传入字典的模型项是类型 A,但此字典需要类型 B 的模型项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10924507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com