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:

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.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">
    <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="" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
            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><a class="btn btn-default" href="">Learn more &raquo;</a></p>
    <div class="col-md-4">
    <div class="col-md-4">
        @foreach (var item in @Model)

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 mvc from when I hosted my website there.