Friday, July 17, 2015

Using TagBuilders in ASP.NET MVC

If you are relatively unfamiliar with developing in ASP.NET MVC, you may be developing code the "hard way" by using a StringBuilder to generate HTML strings and outputting them into your MVC Razor Views.

Well, fortunately, there is a much easier way to accomplish this through using HTML TagBuilders!  Using the TagBuilder is outlined in this article: http://www.asp.net/mvc/overview/older-versions-1/views/using-the-tagbuilder-class-to-build-html-helpers-cs

Therefore, if you want to output a custom Label Control to your ASP.NET MVC Razor View, you might use code like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace ASPNETMVC.HtmlHelpers
{
    public static class HtmlTagHelpers
    {
        public static MvcHtmlString RenderLabelTag(this HtmlHelper helper)
        {
            var labelTagBuilder = new TagBuilder("label");
            labelTagBuilder.AddCssClass("control-label");
            labelTagBuilder.Attributes.Add("title", "someTitle");
 
            var spanTagBuilder = new TagBuilder("span");
            spanTagBuilder.Attributes.Add("style", "color:red");
            spanTagBuilder.SetInnerText("My TagBuilder Label control");
 
            labelTagBuilder.InnerHtml = spanTagBuilder.ToString();
            return MvcHtmlString.Create(labelTagBuilder.ToString());
        }
    }
}


Then in  your Razor View, you simply use code like the following:



@model IEnumerable<System.Security.Claims.Claim>
@using ASPNETMVC.HtmlHelpers
@{
    ViewBag.Title = "Home Page";
}
 
<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>
 
<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        @Html.RenderLabelTag()
    </div>
    <div class="col-md-4">
        @foreach (var item in @Model)
            {
                <p>@item.Value</p>
            }
    </div>
</div>

That is all there is to it!!

1 comment:

  1. Hey, Nice information about ASP.NET MVC. Thanks to share. I have some knowledge about asp.net mvc from Myasp.net when I hosted my website there.

    ReplyDelete