简体   繁体   中英

Is this code business logic or presentation logic?

This code exists in a View:

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

at first glance, it's presentation logic and so it's ok. But it's not sitting well with me.

The thing is, it's a business requirement to display contact info if the group is classified as premium, which means they paid.

What do you guys think? Should this logic be moved into a HtmlHelper or abstracted away by some other means? Or is this the intended usage of the View? What's the best thing to do with this code?

I'd produce a ViewModel that encapsulates this logic as a boolean DisplayContactInfo property. It depends on how "clean" you want your views.

I would definitely move this into a ViewHelper. This is so because once you start writing view logic in the views - aspx files - you start creating 'tag soup' which decreases code understandability and thus increases maintenance cost.

Another benefit of using ViewHelpers to encapsulate your view logic is that it also makes your application more pliable to unit testing. So given your above code I would use it in a ViewHelper like so,

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.
}

Subsequently, somewhere in your view, I would call this helper method like so,

<% Html.ShowContactInfo(Model); %>

This technique results in views which avoid the 'tag soup', are more maintainable and immensely unit testable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM