使用 Visual Studio 设置的默认 MVC 项目,我有一个 _ViewStart.cshtml
文件,用于设置共享的“主” View 。
我目前正在研究以下断言:只要有可能,您就应该使用强类型 View ,因为这样感觉更干净。 (如有错误请指正)
我正在考虑让我的共享“主” View 接受 PageModel
,其中可能包含 PageTitle
、User
、地点
等
我的所有数据模型是否都应该从 PageModel
继承,以便“主” View 和不同的页面 View 可以处理不同类型的模型?我只是想了解一下 MVC 最佳实践。
模型
public class PageModel {
public string Title { get; set; }
}
public class DataModel : PageModel {
public int ID { get; set; }
public DateTime Timestamp { get; set; }
}
_Layout.cshtml
@model Namespace.Models.PageModel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@Model.Title - Website Name</title>
<!-- etc etc -->
Index.cshtml
@model Namespace.Models.DataModel
编辑
假设上述方法是合理的,当“主” View 仍然需要单个模型时,您将如何处理应该接受项目列表的 View ?
_Layout.cshtml
@model Namespace.Models.PageModel
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@Model.Title - Website Name</title>
<!-- etc etc -->
Index.cshtml
@model IEnumerable<Namespace.Models.DataModel>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ID)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ID)
</td>
</tr>
}
</table>
最佳答案
因此,模型的包装实际上是在创建 View 模型, View 模型通常包含您的模型以及您可能需要的任何其他 View 数据。创建 View 模型基类是确保 View 模型一致性的好方法。
然后,您可以完全按照您所描述的方式使用 View 模型库(即在 _Layout 类中设置 @model)。
总而言之 - 你的方法完全没问题,只是术语可能略有不同。
编辑:19/12/2013 0 RE:基于列表的 View
处理此问题的最简单方法是将项目列表公开为 View 模型的属性 - 即不要使用 @model IEnumerable 而是创建一个公开 IEnumerable 的 View 模型,例如:
如果您有 Book 类型的模型:
public class Book { ... }
以及 View 模型(或您所说的 PageModel)基础
public abstract class ViewModelBase {
public string Title { get; set; }
}
你会有一个像这样的 View 模型:
public class BooksViewModel : ViewModelBase {
public IEnumerable<Namespace.Models.DataModel> Books { get; set;}
}
关于c# - 强类型 View 和共享 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20662952/