gpt4 book ai didi

c# - 无法让 DropDownList 与 ViewModel 一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:45 24 4
gpt4 key购买 nike

我目前为博客设置了一个 ViewModel:

public class PostViewModel
{
public string Title { get; set; }
public DateTime DateCreated { get; set; }
public string Content { get; set; }
public int CommentCount { get; set; }
public ICollection<Topic> Topics { get; set; }
public ICollection<Comment> Comments { get; set; }
}

与 Controller 完美配合:

private MyDB db = new MyDB();

public ActionResult Index()
{
var posts = (from p in db.Set<BlogPost>()
select new PostViewModel
{
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
}).ToList();

return View(posts);
}

鉴于这两个部分,我能够遍历列表并生成一篇包含相应评论和主题的博文。但是,我希望在其中包含主题列表的一侧有一个下拉列表。我猜我还需要更改我的 ViewModel 和 HomeController,但我只是不确定该怎么做。

@Html.DropDownListFor(???????)

然后会进入我的 Index.cshtml,但我不知道当其他所有内容都以列表形式出现时我将如何处理?

最佳答案

您可以调整 View 模型,使其包含 View 所需的所有必要信息。所以你提到了一些关于帖子列表和主题下拉列表的内容。所以它非常简单:

public class BlogViewModel
{
public PostViewModel Post { get; set; }

public string TopicID { get; set; }
public IEnumerable<SelectListItem> Topics { get; set; }
}

然后您当然必须调整您的 Controller 操作,以便它从您的后端层获取所有必需的信息并创建适当的 View 模型以传递给 View :

public ActionResult Index()
{
var posts = (from p in db.Set<BlogPost>()
select new PostViewModel
{
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
}).ToList();

IEnumerable<Topic> topics = ... go ahead and fetch the topics you want to show in the ddl

var blog = new BlogViewModel
{
Posts = posts,
Topics = topics.Select(t => new SelectListItem
{
Value = t.ID,
Text = t.TopicText
})
};
return View(blog);
}

最后是 View :

@model BlogViewModel
...
@Html.DropDownListFor(x => x.TopicID, Model.Topics)

当您想在帖子上循环或进行某些操作时,只需使用 Model.Posts在您之前使用的 View 中 Model直接是因为您的 View 被强类型化为 IEnumerable<PostViewModel> .

关于c# - 无法让 DropDownList 与 ViewModel 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10144558/

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