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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With