在_layout中引用一个全局基本模型.其他视图中的CSHTML和自定义模型

本文关键字:模型 其他 视图 CSHTML 自定义 一个 引用 layout 全局 | 更新日期: 2023-09-27 18:15:23

我有两个控制器:HomeControllerCustomersController(第二个控制器已使用vs.net添加支架项目对话框生成)

我创建了这个base view model_layout.cshtml一起工作(传递数据,如应用程序名称,元描述和其他全局信息,从DB中提取/根据用户的语言设置更改)

public abstract class BaseViewModel
{
    public string AppName { get; set; }
    public string Author { get; set; }
    public string PageTitle { get; set; }
    ...
}

然后我从它派生出另一个CommonModel:

    public class CommonModel: BaseViewModel

这样我就可以使用我的HomeController(),即

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string LocalizedTitle = "Greeting in user language...";
        CommonModel Model = new CommonModel { PageTitle = LocalizedTitle };
        return View(Model);
    }
    ...

然后,在_layout.cshtml中,我有这样的内容:

@model PROJECT_NAME.Models.CommonModel
<!DOCTYPE html>
<html>
<head>
    <title>@Model.PageTitle - @Model.AppName</title>
    ...

问题是,如果用户试图访问Customers/Index,这不起作用,在这种情况下,我得到了可怕的错误The model item passed into the dictionary is of type

客户/索引。CSHTML看起来像这样:

@model IEnumerable<PROJECT_NAME.Models.Customer>
<h2>Show your list here...</h2>
...

我的CustomersController是这样的:

public class CustomersController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();
    // GET: Customers
    public ActionResult Index()
    {
        return View(db.Customers.ToList());
    }

我的问题是我如何使每个视图调用自己的模型而不相互干扰?

换句话说,我如何使_Layout.cshtml引用@model PROJECT_NAME.Models.CommonModel,而Customers/Index.cshtml引用@model IEnumerable<PROJECT_NAME.Models.Customer>而没有错误?


免责声明!

  1. 我很新的asp.net MVC,请很好!
  2. 是的,我以前确实看了很多,但我在SO中发现的问题/答案都没有解决我的问题(要么就是我不理解他们)

在_layout中引用一个全局基本模型.其他视图中的CSHTML和自定义模型

您的基本视图模型是BaseViewModel(它包含您想要在布局中显示的属性),因此您的_Layout.cshtml文件应该有

@model PROJECT_NAME.Models.BaseViewModel // not CommonModel

然后所有使用该布局的视图都需要使用从该基本模型派生的视图模型,因此在显示IEnumerable<Customer>的视图的情况下,该视图的视图模型将是

public class CustomerListVM : BaseViewModel
{
    public IEnumerable<Customer> Customers { get; set; }
}

和该视图的GET方法

string LocalizedTitle = "Greeting in user language...";
CustomerListVM model = new CustomerListVM()
{
    PageTitle = LocalizedTitle,
    ... // other properties of BaseViewModel
    Customers = db.Customers
}
return View(model);

,然后视图将是

@model CustomerListVM
....
@foreach(var customer in Model.Customers
{
    ....

我不确定我理解对了。

但是你想在视图中使用2个模型?

让我们说:

modelA用于布局

要在网页中使用的ModelB吗?

之类的

2个模型的操作结果?

如果这是正确的,你可以这样做

List<ModelB> = ....填补它

返回视图(模型、ModelB);

看起来像:

return View(db.Model.ToList(),ModelB);

和在布局中使用@Model,对于网页,你可以使用你的ModelB(不是@Model)

这不是最好的选择。但也许这是帮助你的开始。