Tuesday, October 27, 2009

Codename 'DiscMaster' - Implementing custom HtmlHelpers

ASP.NET MVC has great support for writing your own HtmlHelpers, here's an example I wrote that takes a model of a player and outputs the profile picture (if any).

So now outputting the profile picture is trivial and from one source:
<%= Html.ProfileImage(Model, "", null, "70", new {style="float: left; padding-right: 10px; padding-bottom: 10px;"})  %>

The code below is the entire code that generates my helper. it's actually a extension method on the HtmlHelper class that uses a TagBuilder. diving further into that you could write class-specific helpers simply by adding the type to the param, like HtmlHelper<Player>..

using DiscMaster.Web.Models;
using DiscMaster.Web.Extensions;

namespace DiscMaster.Web.Helpers
{
    public static class ProfileImageHelper
    {
        public static string ProfileImage(this HtmlHelper helper, Models.Player player, string alternateText, string width, string height)
        {
            return ProfileImage(helper, player, alternateText, width, height, null);
        }

        public static string ProfileImage(this HtmlHelper helper, Models.Player player, string alternateText, string width, string height, object htmlAttributes)
        {
            // Create tag builder
            var builder = new TagBuilder("img");

            // Create valid id
            builder.GenerateId(player.UserName);

            // Add attributes
            string format = "{0}/{1}";
            if (!string.IsNullOrEmpty(width))
            {
                format = format + "&width={2}";
            }
            if (!string.IsNullOrEmpty(height))
            {
                format = format + "&height={3}";
            }

            builder.MergeAttribute("src", string.Format(format,"/Image.ashx?src=/Content/Media/Images/Players/",player.PlayerDetail.profilepicture.IfEmptyThen("noprofilepicture.png"),width,height));
            builder.MergeAttribute("alt", alternateText.IfEmptyThen(player.UserName));
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            // Render tag
            return builder.ToString(TagRenderMode.SelfClosing);
        }
    }
}

As always, the url to Codename 'DiscMaster': http://discmaster.codeplex.com/


Regards,

P.

No comments: