Working with Blog Categories in Razor Views

Scott Walker · Aug 13, 2013
Working with Blog Categories in Razor Views

In this example, a blog post can be associated with multiple categories (MVC3, Razor, etc.). To allow editors to select which categories apply to a blog, the view loops through all available categories and renders a checkbox for each one.

The CheckCategory helper function determines whether a given category is already assigned to the blog. If so, the checkbox is rendered as checked.

Razor View


@foreach (MVC3.Models.Category cat in ViewBag.Categories) { @Html.CheckBox( cat.BlogCategoryTitle, CheckCategory(Model.BlogID, cat.CategoryID) ) @cat.BlogCategoryTitle } @functions { public bool CheckCategory(int blogId, int categoryId) { foreach (MVC3.Models.BlogsCategories assigned in ViewBag.SelectedCategories) { if (assigned.BlogID == blogId && assigned.CategoryID == categoryId) { return true; } } return false; } }

This approach makes it easy to display all categories and automatically mark the ones already linked to the blog. Although newer versions of ASP.NET MVC and Razor Pages offer more modern patterns (such as strongly typed view models or tag helpers), this technique remains effective for legacy MVC3 applications.

Razor

Comments (0)

Please sign in to comment.