ASP.NET MVC Helper - MoreLessText
|« Previous article:||Next article: »|
|Throwback Thursday - C++ Iterator of the Week||Blog Home||First Non-Repeating Character - My Solution|
Large blocks of text are often unwieldy (and ugly) on webpages. But, sometimes, we just need all that text available. A common way to deal with this is to initially display just an excerpt of the whole text block, but allow the user to “open up” the text to reveal the full version. I use this technique when displaying show description on my other site, NJTheater.com
So, let’s look at how this is handled. It is implemented in ASP.NET MVC as a Helper. It’s called like this:
<div class="Description"> @Html.MoreLessText(Model.Description, 100) </div>
The two parameters are the long text to be displayed, and the maximum number of characters to display before hiding the rest. These are followed by two optional parameters, text which will be used for button to “open” and “close” the text, but here’s we’re just using their defaults, “(more)” and “(less)” respectively.
The code is fairly straightforward, but that leads rather dull blog articles, so let’s elaborate.
First we check if the text is short enough to display straight. If so, we just return it, and move on.
Then, we search for the last space before the maximum length – so we don’t chop off a word in the middle – and use that to build the Html for our text. It will look like this.
[Truncate text] <span id="extraText-12ABF3D"> [Remainder of text] <a onclick="moreless('12ABF3D');">(less)</a> </span> <span id="more-12ABF3D" style="display:none"> <a onclick="moreless('12ABF3D');">(more)</a> </span>
The value “12ABF3D” is a random id generated new each time. It’s based on a GUID, but shorted to be less unwieldy (however, also now no longer guaranteed to be unique, although collisions on a page are unlikely).
The onclicks call the moreless function we defined before, which toggles the extra text on & off (and also which button in displayed).