2

在我的网站上,我不想在几乎每个页面上显示来自数据库的类别列表。目前我使用 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 中引用了 HtmlHelper 而不是 System.Web.Mvc。这是我正在使用的代码:

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

}
4

1 回答 1

1

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

@Html.ShowCategories()
于 2012-04-19T20:52:03.653 回答