views:

133

answers:

2

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?

+9  A: 

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

Daz Lewis
+1 IMO, this is a perfect use of the ViewModel properties
Gregoire
I want the views as clean as possible, within reason. I'm trying to put together a best-practices guide for a project we're working on and I want to make sure the suggestions I put in it make sense and are reasonable.
DaveDev
+1  A: 

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.

Bikal Gurung