c# - (asp.net MVC4) 在 _layout.cshtml 中引用全局基本模型并在其他 View 中引用自定义模型?

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

我有两个 Controller :HomeControllerCustomersController (第二个 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>没有错误?


免责声明!

  1. 我对 ASP.NET MVC 很陌生,请多多指教!
  2. 是的,我之前确实看了很多,但是我在 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/

相关文章:

c# - Nest SuggestCompletion用法,抛出 'is not a completion suggest field'异常

c# - 在 Visual Studio 中生成类。方法需要建议

asp.net-mvc - 如何本地化/更改 DataAnnotation 的必填字段验证器?

asp.net-mvc - 使用变量时 DonutOutputCache 不会清除缓存

asp.net - 如何让 Npgsql 连接到 Postgresql 9.5

c# - LINQ 检查是否为 int?在 List<Int> C# 中

c# - 如何通过WebApi上传图片

c# - 临时在网络服务上保存文件的位置

asp.net - 如何允许我的 Azure Web 应用程序访问 Active Directory?

c# - 无法确定元表