gpt4 book ai didi

asp.net-mvc - MVC - View 中的多个模型

转载 作者:行者123 更新时间:2023-12-01 22:40:41 24 4
gpt4 key购买 nike

我(第一次)使用 MVC 和 Entity Framework ,首先是数据库

我想要做的是在单个 View 中显示数据库中的数据。我首先创建了数据库,然后根据包含所有表的数据库创建了一个 ADO.NET 实体数据模型。然后,我创建了一个以我的实体数据模型作为模型的强类型索引 View 。

在我的索引中,我位于顶部

@model IEnumerable<Forum6.Models.Forum>

这允许我从数据库中获取表“Forum”中的行。如果我尝试添加额外的模型,我会在运行时收到此错误消息:

Line 1: @model IEnumerable<Forum6.Models.Forum>
Line 2: @model2 IEnumerable<Forum6.Models.Post>

Parser Error Message: Only one 'model' statement is allowed in a file.

在寻找答案后,我发现了这个:Two models in one view in ASP MVC 3答案是创建一个包含所有模型(表)的 ViewModel(ParentModel)。这是我创建的 ViewModel:

public class ViewModel
{
public IEnumerable<Forum6.Models.Forum> Forum { get; set; }
public IEnumerable<Forum6.Models.Post> Post { get; set; }
public IEnumerable<Forum6.Models.Topics> Topics { get; set; }
public IEnumerable<Forum6.Models.Users> Users { get; set; }
public IEnumerable<Forum6.Models.PrivMsg> PrivMsg { get; set; }
public IEnumerable<Forum6.Models.Permission> Permission { get; set; }
}

我编辑了我的 Controller ,如下所示:

   public class HomeController : Controller
{
// ForumDBEntities old_db = new ForumDBEntities();

ViewModel db = new ViewModel();

public ActionResult Index()
{
return View(db);
}
}

然后用使用 ViewModel 作为模型的新强类型 View 替换旧的 Index View 。其中包含:

@model IEnumerable<Forum6.Models.ViewModel>

尝试运行此命令会出现此错误:

The model item passed into the dictionary is of type 'Forum6.Models.ViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Forum6.Models.ViewModel]

如何使“ViewModel”可枚举?还是我的错误在其他地方?

最佳答案

您需要更改@model IEnumerable<Forum6.Models.ViewModel>@model Forum6.Models.ViewModel当您将 IEnumerables 包装在单个 ViewModel 中时。

一个好的经验法则是 ViewModel 和 View 之间保持 1:1 的关系。 enter image description here

这对您来说可能是一本不错的读物:http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/ (如果您不想走那条路,请忽略自动映射器部分)

您还需要在 ViewModel 中输入实际数据

ViewModel db = new ViewModel();

public ActionResult Index()
{
return View(db);
}

只会给你的 View 一个空的ViewModel。一种方法是。

public ActionResult Index()
{
var model = new ViewModel
{
Forum = db.GetForum(),
Post = db.GetPost(),
Topic = you get the idea
};

return View(model);
}

最后一件事是,在命名属性或变量时,当它包含列表时,您应该使用复数动词。所以你的 ViewModel 就是。

public class ViewModel
{
public IEnumerable<Forum6.Models.Forum> Forums { get; set; }
public IEnumerable<Forum6.Models.Post> Posts { get; set; }
public IEnumerable<Forum6.Models.Topics> Topics { get; set; }
public IEnumerable<Forum6.Models.Users> Users { get; set; }
public IEnumerable<Forum6.Models.PrivMsg> PrivMsgs { get; set; }
public IEnumerable<Forum6.Models.Permission> Permissions { get; set; }
}

关于asp.net-mvc - MVC - View 中的多个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15360557/

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