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

标签 c# asp.net asp.net-mvc-3 razor

我目前为博客设置了一个 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/

相关文章:

c# - Windows 8 Metro ListView - 无法禁用 ScrollViewer (C#/XAML)

c# - .NET 中的动态控件问题

c# - 根据类型处理字典中的泛型方法

c# - 点击刷新网页后,再次触发 Button1_Click 事件

asp.net - 分页GridView

c# - 进程 'C:\hostedtoolcache\windows\dotnet\dotnet.exe' 失败,退出代码 1

ASP.NET 核心 : log all requests (reading body twice) EnableRewind not working for [FromBody] attribute

jquery - 自定义 ValidationSummary 模板(不会破坏客户端验证)

asp.net-mvc-3 - MVC 配置授权角色值和强类型角色

c# - 无法在多封电子邮件中重复使用电子邮件附件