这是代码业务逻辑还是表示逻辑?

此代码存在于视图中:

if (Model.Group.IsPremium && null != Model.Group.ContactInfo) { Html.RenderPartial("ContactInfo", Model.Group.ContactInfo); } 

乍一看,这是演示逻辑,所以没关系。 但它并不适合我。

问题是,如果该组被归类为高级,这意味着他们已付款,则显示联系信息是业务要求。

你们有什么感想? 这个逻辑应该转移到HtmlHelper中还是通过其他方式抽象出来? 或者这是View的预期用途? 这段代码最好的做法是什么?

我将生成一个ViewModel,它将此逻辑封装为布尔DisplayContactInfo属性。 这取决于你希望你的观点“干净”。

我肯定会把它移到ViewHelper中。 这是因为一旦你开始在视图中编写视图逻辑–aspx文件 – 你开始创建’标签汤’,这会降低代码的可理解性,从而增加维护成本。

使用ViewHelpers封装视图逻辑的另一个好处是,它还使您的应用程序对unit testing更加柔韧。 所以考虑到上面的代码,我会在ViewHelper中使用它,就像这样,

 using System.Linq; using System.Web.Mvc; using System; using System.Text; using System.Web.Mvc.Html; //Need this for Html helper extension method public static class GroupViewHelper { public static void ShowContactInfo(this HtmlHelper helper, ModelType model) { if (model.Group.IsPremium && null != model.Group.ContactInfo) { //Do your rendering here. } } // ... your other ViewHelper methods here. } 

随后,在你看来的某个地方,我会像这样调用这个辅助方法,

 <% Html.ShowContactInfo(Model); %> 

这种技术产生的视图避免了“标签汤”,更易于维护和极其可测试的单元。