我听说在 View 中使用 @foreach 是禁忌。意思是, View 中不应该有任何逻辑。 @foreach 的逻辑应该位于何处的最佳实践是什么?
@foreach..
最佳答案
What is the best practice on where the logic for the @foreach should be at?
无处可去,就摆脱它吧。您可以使用编辑器或显示模板。
例如:
@foreach (var item in Model.Foos)
{
<div>@item.Bar</div>
}
完全可以用显示模板替换:
@Html.DisplayFor(x => x.Foos)
然后您将定义相应的显示模板(如果您不喜欢 default one )。所以你可以定义一个可重用的模板 ~/Views/Shared/DisplayTemplates/Foo.cshtml
框架将自动为 Foos 集合 ( IEnumerable<Foo> Foos { get; set; }
) 的每个元素呈现:
@model Foo
<div>@Model.Bar</div>
显然,完全相同的约定适用于编辑器模板,如果您想要显示一些输入字段,允许您编辑 View 模型,而不是仅将其显示为只读,则应使用该约定。
关于asp.net-mvc - MVC Razor @foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11261590/