Reputation: 241
On my site i wan't to display a list of categories from a db on almost every page. At the time being i use the ViewBag to store the categories, but I know there must be some better way. Therefore i'm wondering about best practices when loading re-occurring elements in MVC3.
Here's some code:
public class HomeController : Controller
{
private AlltForMusikContext db = new AlltForMusikContext();
//
// GET: /Admin/
public ViewResult Index()
{
var ads = db.Ads.Include(a => a.Category).OrderByDescending(a => a.Date);
ViewBag.Categories = db.Categories.ToList();
return View(ads.ToList());
}
public ViewResult Category(int id)
{
var ads = db.Ads.Where(a => a.Category.CategoryId == id).OrderByDescending(a => a.Date);
ViewBag.Categories = db.Categories.ToList();
ViewBag.Category = db.Categories.Where(a => a.CategoryId == id).FirstOrDefault();
return View(ads.ToList());
}
}
I use this code in the _Layout.cshtml
@Html.Partial("_GetCategories", (IEnumerable<AlltForMusik.Models.Category>)@ViewBag.Categories)
This is my partial view that I load into the layout view:
@model IEnumerable<AlltForMusik.Models.Category>
@foreach (var cat in Model)
{
<img src="@Url.Content("~/Content/img/icon_arrow.gif")" />
@Html.ActionLink(cat.CategoryName, "Category", "Home", new { id = cat.CategoryId })<br />
}
This works but I have to load the categories into the ViewBag every time I wanna load a view, othervise I get an error.
What is the best way to load content like this?
Answer:
I followed the advice and used a HtmlHelper. I stumbled upon some problems at first because i hade referenced the HtmlHelper in System.Web.Webpages instead of System.Web.Mvc. Here's the code i'm using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AlltForMusik.Models;
using System.Web.Mvc;
namespace AlltForMusik.Helpers
{
public static class HtmlHelpers
{
public static string GetCategories(this HtmlHelper helper)
{
AlltForMusikContext db = new AlltForMusikContext();
var categories = db.Categories.OrderBy(a => a.CategoryName).ToList();
string htmlOutput = "";
foreach (var item in categories)
{
htmlOutput += item.CategoryName + "<br />";
}
return htmlOutput.ToString();
}
}
}
Upvotes: 2
Views: 73
Reputation: 10067
Create custom HttpHelper with Caching. for example ShowCategories(). and then just put it on the view or on the common layout like:
@Html.ShowCategories()
Upvotes: 1