Friday, May 23, 2014

SafeSubstring Extension Method

Extension methods are a great way to keep you’re view code tight and readable.  I always include a UIExtensionMethods class in my projects that contains extensions for the HtmlHelper and for my View Model classes.

The Problem

I often want to restrict the max number of characters that will display in the UI.  If a field has 2000 characters, I just want to show the first 100.  Easily done right?  Just use a substring like so:

<div> @Model.JobSummary.Substring(0, 300) <a href="#" class="empub_feed_readmore_link">read more...</a> </div>

The problem is that there are a number of things that will make Substring throw errors.  If JobSummary is null, error.  If JobSummary has less than 300 characters, error.  I can check for these things in my view code, but that’s going to make my view look messy and I’ll have to copy and paste that code every time I do a substring in a view.

A Quick Solution

Anytime I have view code that needs to be used more than once, or even hurts the readability of my view, I extract that code into an extension method.  Since I want a version of Substring that I can run in a view without throwing an error, I call the method SafeSubstring.

// SafeSubstring public static MvcHtmlString SafeSubstring(this HtmlHelper htmlHelper, string text, int start, int stop) { if (string.IsNullOrEmpty(text) || text.Length < (start + stop)) { return new MvcHtmlString(text); } return new MvcHtmlString(text.Substring(start, stop)); }

Now my view code looks clean, and I have another tool in my toolbox that can be used next time

<div> @Html.SafeSubstring(Model.JobSummary, 0, 300) <a href="#" class="empub_feed_readmore_link">read more...</a> </div>