In this example, each blog post can have multiple categories associated with it. Both the blog data and category data are stored in the database, so the goal is to expose a list of categories for a specific blog inside the view.
The solution is to add a method to the Blog model that retrieves all categories linked to the blog and returns them as a SelectList. This makes it easy to display categories as links or inside a dropdown list.
Blog Model Method
The following method queries the database, finds all categories associated with the blog, and returns them as a SelectList:
public SelectList GetCategories()
{
BlogsDataContext db = new BlogsDataContext();
ArrayList arr = new ArrayList();
IQueryable result = (IQueryable)(
from cats in db.Categories
join list in db.BlogsCategories
on cats.CategoryID equals list.CategoryID
where list.BlogID == _BlogID
select new SelectListItem { Text = cats.Title }
);
foreach (SelectListItem item in result)
{
arr.Add(item.Text);
}
return new SelectList(arr);
}
This method returns a simple list of category titles, which can be used in multiple ways inside the view.
Using Categories in the View
Once the model exposes GetCategories(), the view can loop through the categories or bind them to a dropdown list.
Displaying Category Links
<% foreach (System.Web.Mvc.SelectListItem item in blog.GetCategories()) { %>
<%: Html.ActionLink(item.Text, item.Text, "Categories") %>
<% } %>
Dropdown List of Categories
Categories
<%: Html.DropDownList("Categories", blog.GetCategories()) %>
This approach keeps your view clean and allows the model to handle the logic of retrieving category data. Although newer versions of ASP.NET MVC encourage strongly typed view models instead of using ViewBag or model methods, this pattern remains effective for legacy MVC applications.
Comments (0)
Please sign in to comment.