我目前为博客设置了一个 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
在您之前使用 Model
的 View 中直接因为您的 View 被强类型化为 IEnumerable<PostViewModel>
.
关于c# - 无法让 DropDownList 与 ViewModel 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10144558/