【问题标题】:Adding a Categorylist to all pages with MVC4使用 MVC4 将 Categorylist 添加到所有页面
【发布时间】:2012-11-21 10:23:34
【问题描述】:

我是 MVC4 的新手,只是 MVC。

我有一个homecontroller 和一个categorycontrollercategorycontroller 将数据从模型发送到 categoryIndex 视图。这很好用。

但现在我想在所有可用的控制器上添加categorylist

我已经修复了这个问题以添加所有类 return view(db.categorys.ToList()); 并将 categoryIndex 添加到共享文件夹中。在_layout.cshtml 中,我添加了一个@RenderPage("~/")`,这样就可以了。

但是,当我必须在返回中传递的不仅仅是 (db.categorys.ToList()) 时,它就会出错。

我该如何解决这个问题。如何正确添加每个控制器和页面的类别列表?

【问题讨论】:

  • 出了什么问题?有任何错误信息吗?

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

CategoryList 集合作为属性添加到您的 ViewModels(所有页面)。您可以将其添加到基类中并从中继承。

public class Category
{
  public int ID { set;get;}
  public string Name { set;get;}
}
public class BasePageViewModel
{
  public List<Category> CategoryList { set;get;}

  BasePageViewModel()
  {
    CategoryList=new List<Category>();
  }
}

现在您可以从这个基类继承其他视图模型。

public class ProductViewModel : BasePageViewModel
{
  public string ProductName { set;get;}
  //Other properties
}

现在在您的视图中,它是 ProductViewModel 的强类型,您可以调用 Html.Partial 来显示 CategoryList 部分视图。

@model ProductViewModel
<h3>This page is for product @Model.ProductName</h3>
@Html.Partial(Model.CategoryList)

假设您有一个部分视图来呈现 CategoryList

【讨论】:

    【解决方案2】:

    我建议将常用的东西(例如类别列表)放入 ViewBag。这将允许您进行一些分离,并且只返回需要存在的视图。希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      相关资源
      最近更新 更多