Building custom HTML tags

It is possible to create some pretty complicated custom HTML using Build.Mvc... 

@( Html.BuildTag("a").Href("~/Services/OData.svc").AddClass("feed").With(x => {
        x.InternalBuilder.InnerHtml = Html.BuildTag("img").
            Src("~/Content/Img/icon-odatafeed-28x28.png").
            Alt("OData Feed").
            ToHtmlString();
    }))

This is the equivalent to:

<a class="feed" href="@Url.Content("~/Services/OData.svc")">
    <img alt="OData Feed" src="@Url.Content("~/Content/Img/icon-odatafeed-28x28.png")" /></a>

One could certainly argue that the example about isn't any easier than just building HTML markup... but it gets interesting when you start adding your own Build.Mvc extensions:

 

public static IHtmlTagBuilder BuildImageLink(this HtmlHelper htmlHelper, string imgSrc, string imgAlt = null)
{
    return htmlHelper.BuildTag("a").With(x =>
    {
        x.InternalBuilder.InnerHtml = htmlHelper.BuildTag("img", TagRenderMode.SelfClosing).
            Src(imgSrc).
            AttrWhen(!string.IsNullOrEmpty(imgAlt), "alt", imgAlt).
            ToHtmlString();
    });
}

 

Then you can do this:

 

@( Html.BuildImageLink("~/Content/Img/icon-odatafeed-28x28.png", "OData Feed").
        Href("~/Services/OData.svc").
        AddClass("feed"))

Last edited Dec 22, 2011 at 6:35 PM by grcodemonkey, version 7

Comments

No comments yet.