MVC剃刀@foreach [英] MVC Razor @foreach

查看:227
本文介绍了MVC剃刀@foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说有@foreach视图里面是一个没有没有。意,该视图应该没有任何逻辑它。什么是其中用于@foreach逻辑应在最佳做法?

  @foreach ..


解决方案

  

什么是其中用于@foreach逻辑应该是最好的做法?


行不通的,只是摆脱它。你可以使用编辑器或显示模板。

因此​​,例如:

  @foreach(在Model.Foos VAR项)
{
    < D​​IV> @ item.Bar< / DIV>
}

可以完美的罚款由显示模板替换:

  @ Html.DisplayFor(X => x.Foos)

,然后你会定义相应的显示模板(如果你不喜欢<一个href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html/\">default 之一)。所以,你会定义一个可重复使用的模板〜/查看/共享/ DisplayTemplates / Foo.cshtml ,它会自动被框架的集合FOOS的每个元素被渲染(的IEnumerable&LT;富&GT; FOOS {获取;设置;}

  @model富
&LT; D​​IV&GT; @ Model.Bar&LT; / DIV&GT;

显然完全相同的约定申请应在情况下使用编辑模板,你想展示一些输入字段让您编辑在对比视图模型只显示它为只读。

I heard that having @foreach inside of a view is a no-no. Meaning, the view should not have any logic in it. What is the best practice on where the logic for the @foreach should be at?

    @foreach.. 

解决方案

What is the best practice on where the logic for the @foreach should be at?

Nowhere, just get rid of it. You could use editor or display templates.

So for example:

@foreach (var item in Model.Foos)
{
    <div>@item.Bar</div>
}

could perfectly fine be replaced by a display template:

@Html.DisplayFor(x => x.Foos)

and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }):

@model Foo
<div>@Model.Bar</div>

Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.

这篇关于MVC剃刀@foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆