(asp.net MVC4)引用_layout.cshtml中的全局基本模型和其他视图中的自定义模型?

时间:2016-10-28 22:15:00

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我有两个控制器:HomeControllerCustomersController(第二个控制器是使用vs.net add scafolded item对话框生成的)

我创建了这个与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());
    }

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

换句话说,我如何在没有错误的情况下_Layout.cshtml引用@model PROJECT_NAME.Models.CommonModel Customers/Index.cshtml引用@model IEnumerable<PROJECT_NAME.Models.Customer>

声明!

  1. 我是asp.net MVC的新手,请你好!
  2. 是的,之前我确实看了很多,但我在SO中找到的问题/答案都没有解决我的问题(或者我没有理解它们)

2 个答案:

答案 0 :(得分:2)

您的基本视图模型是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
{
    ....

答案 1 :(得分:0)

我不确定我是否理解。

但您想在视图中使用2个模型吗?

让我们说:

用于布局的modelA

要在网页中使用的ModelB吗?

类似

使用2个模型的Actionresult?

如果那是对的,你可以做这样的事情

List<ModelB> = ....填写

返回视图(ModelA,ModelB);

看起来像:

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

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

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