Reputation:
I currently have a ViewModel set up for a blog:
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; }
}
Which works perfectly with the 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);
}
Given these two parts, I am able to foreach through the list and generate a blog post with corresponding comments and topics just fine. However, I would like to have a drop down list off to the side that has a list of topics in it. I am guessing I need to alter my ViewModel and HomeController as well, but I am just unsure of how to do that.
@Html.DropDownListFor(???????)
would then go into my Index.cshtml, but I don't know how I'd deal with that when everything else is coming in as a list?
Upvotes: 2
Views: 2126
Reputation: 1038940
You could adapt your view model so that it contains all the necessary information that the view requires. So you mentioned something about a lists of posts and a dropdown of topics. So it is pretty straightforward:
public class BlogViewModel
{
public PostViewModel Post { get; set; }
public string TopicID { get; set; }
public IEnumerable<SelectListItem> Topics { get; set; }
}
and then of course you will have to adapt your controller action so that it fetches all the required information from your backend layers and create the proper view model to be passed to the 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);
}
and finally the view:
@model BlogViewModel
...
@Html.DropDownListFor(x => x.TopicID, Model.Topics)
and when you wanted to loop or something over the posts simply use Model.Posts
in the view where you previously used Model
directly because your view was strongly typed to IEnumerable<PostViewModel>
.
Upvotes: 2