ASP.NET MVC:如何哑应我的看法是什么? [英] ASP.NET MVC: How dumb should my view be?

查看:122
本文介绍了ASP.NET MVC:如何哑应我的看法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我不是在谈论使业务逻辑的决定,而是UI的决定。

Ok, I'm not talking about making business logic decisions, but rather UI decisions.

例如,我在渲染一张桌子和一列显示日期时间?要被格式化需要属性。由于此值可为空,我需要检查,这不是空格式化之前。

For example, I'm rendering a table and one column displays a DateTime? property that needs to be formatted. Because the value is nullable I need to check that it's not null before formatting.

如果我想成为迂腐,我会在我的ViewModel一个FormattedDate属性:

If I wanted to be pedantic, I would have a FormattedDate property on my ViewModel:

public class MyViewModel 
{
    ...
    public DateTime? Date { get; set; }

    public string FormattedDate 
    {
        get 
        {
            return this.Date.HasValue ? this.Date.Value.ToShortDateString() : "";
        }
    }
}

<%= Html.Encode(Model.FormattedDate) %>

或者我可以拯救自己code几行,只是在视图中就打吧:

Or I could save myself a few lines of code and simply slap it in the view:

<%= Html.Encode(Model.Date.HasValue ? Model.Date.Value.ToShortDateString() : "")%> 

在此情况下,因为这是一件只影响来看,我认为它的确定做了第二种方式(也是它更紧凑的),但我在哪里画有我的看法与服务器混乱之间的界线-side code和具有堆满我的视图模型格式属性?

In this case, since this is something that only affects the view, I would argue that it's OK to do it the second way (and also it's more compact) but where do I draw the line between having my view cluttered with server-side code and having my ViewModel cluttered with "formatting" properties?

推荐答案

它并没有真正节省您的相关code中的任何行,如果你把它直接在视图 - 它只是移动它周围

It doesn't really save you any lines of relevant code if you put it directly in the View - it just moves it around.

不过,如果你把它放在视图中,可以只使用它。你不能重复使用视图模型的逻辑在其他地方,你不能单元测试。

However, if you put it in the View, you can only use it there. You can't reuse the ViewModel's logic elsewhere, and you can't unit test it.

请您浏览非常愚蠢的。我要说的是,意见应该有尽可能低的圈复杂的越好。

Keep your Views really dumb. I would say that Views should have as low a Cyclomatic Complexity as possible.

请参阅这个答案了解更多详情。

这篇关于ASP.NET MVC:如何哑应我的看法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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