MVC 3定期重新发生的元素......最佳实践

时间:2012-04-19 20:48:22

标签: asp.net-mvc

在我的网站上,我几乎不会在每个页面上显示数据库中的类别列表。目前我使用ViewBag来存储类别,但我知道必须有更好的方法。因此,我想知道在MVC3中加载重新发生的元素时的最佳实践。

以下是一些代码:

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());
    }
}

我在_Layout.cshtml中使用此代码

 @Html.Partial("_GetCategories", (IEnumerable<AlltForMusik.Models.Category>)@ViewBag.Categories)

这是我加载到布局视图中的部分视图:

@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 />
}

这有效但我每次要加载视图时都必须将类别加载到ViewBag中,否则我会收到错误。

加载此类内容的最佳方式是什么?

答案:

我遵循了建议并使用了HtmlHelper。我最初偶然发现了一些问题因为我在System.Web.Webpages而不是System.Web.Mvc中引用了HtmlHelper。这是我正在使用的代码:

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();
    }
}

}

1 个答案:

答案 0 :(得分:1)

使用缓存创建自定义HttpHelper。例如ShowCategories()。然后将它放在视图或公共布局上,如:

@Html.ShowCategories()