ASP.NET MVC 视图中允许多少逻辑? [英] How much logic is allowed in ASP.NET MVC views?

查看:20
本文介绍了ASP.NET MVC 视图中允许多少逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看 ASP.NET MVC 站点的示例时,我看到了很多在视图中嵌入逻辑的示例,例如:

In looking at samples of ASP.NET MVC sites, I'm seeing quite a bit of examples with embedded logic in the views, e.g.:

<% if (customerIsAllowed)
   { %>

   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>

<% }  else {%>

   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>
   <p>nnn</p>

<% } %>

虽然这对我来说似乎是错误的,因为这是我们在 ASP 3.0 中试图摆脱的那种事情,但我什至在一些播客中听说有一点逻辑是可以的",因为其余部分MVC 框架正在处理我们在 ASP 3.0 中没有的结构.

Although this seems wrong to me since it is the kind of thing we were trying to get away from in ASP 3.0, I have even heard in some podcasts how "a little bit of logic in view is ok" since the rest of the MVC framework is taking care of the structure that we didn't have in ASP 3.0.

是否有任何 MVC 约定指定视图中允许的逻辑类型和数量?

Are there any MVC conventions specifying what kind and how much logic is allowed in views?

推荐答案

这取决于逻辑的原因.如果逻辑是根据控制器传递给它的某些属性选择替代演示文稿,则可能没问题.这允许您重用一些视图.不必为每个自定义权限重新创建(并重复)整个视图,您可以传入一些数据,允许基于此权限自定义视图.

It depends on the reason for the logic. If the logic is choosing an alternate presentation based on some property passed to it by the controller, it is probably ok. This allows you some view reuse. Instead of having to recreate (and repeat) an entire view for each custom privilege, you can pass in some data that allows the view to be customized based on this privilege.

我认为这是理想化 MVC 和严格执行 DRY 之间的务实平衡(不要重复自己).在某些情况下,如果您无法轻松实现两者,则违反其中一项更为明智.在模型和基本视图明显相同的情况下,在视图中添加一些逻辑以保持视图干燥是合理的.

I think of this as a pragmatic balance between an idealized MVC and strict enforcement of DRY (don't repeat yourself). In some situations it is wiser to violate one or the other if you can't attain both easily. In the case where clearly the model and the basic view is the same, putting a little logic in the view to keep your views DRY is reasonable.

这篇关于ASP.NET MVC 视图中允许多少逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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