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?
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:
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:
and finally the view:
and when you wanted to loop or something over the posts simply use
Model.Postsin the view where you previously usedModeldirectly because your view was strongly typed toIEnumerable<PostViewModel>.