我有两个 Controller :HomeController
和CustomersController
(第二个 Controller 是使用 vs.net 添加支架项目对话框生成的)
我创建了这个base view model
适用于 _layout.cshtml
(传递应用程序名称、元描述和其他从数据库提取的全局信息/根据用户设置的语言进行更改的数据)
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
...
Customers/Index.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());
}
我的问题是如何让每个 View 调用自己的模型而不互相干扰?
换句话说,我怎样才能制作_Layout.cshtml
引用@model PROJECT_NAME.Models.CommonModel
,而Customers/Index.cshtml
引用@model IEnumerable<PROJECT_NAME.Models.Customer>
没有错误?
免责声明!
- 我对 ASP.NET MVC 很陌生,请多多指教!
- 是的,我之前确实看了很多,但是我在 SO 中找到的问题/答案都没有解决我的问题(要么是我不理解它们)
最佳答案
您的基本 View 模型是 BaseViewModel
(其中包含您想要在布局中显示的属性),因此您的 _Layout.cshtml
文件应该有
@model PROJECT_NAME.Models.BaseViewModel // not CommonModel
然后,使用该布局的所有 View 都需要使用从该基本模型派生的 View 模型,因此在显示 IEnumerable<Customer>
的 View 的情况下,该 View 的 View 模型将是
public class CustomerListVM : BaseViewModel
{
public IEnumerable<Customer> Customers { get; set; }
}
以及该 View 的 GET 方法
string LocalizedTitle = "Greeting in user language...";
CustomerListVM model = new CustomerListVM()
{
PageTitle = LocalizedTitle,
... // other properties of BaseViewModel
Customers = db.Customers
}
return View(model);
然后 View 将是
@model CustomerListVM
....
@foreach(var customer in Model.Customers
{
....
关于c# - (asp.net MVC4) 在 _layout.cshtml 中引用全局基本模型并在其他 View 中引用自定义模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313915/