简体   繁体   中英

What is the difference between Tagbuilder and @helper

I don't understand what the difference is between a tagbuilder and @helper

For example:

@helper TestHelper(string name , string id , int value)
{
    if(value>3)
    {
        <p name="@name" id="@id">@value</p>
    }
}

The helper can create a tag, so why or when we use the tagbuilder?

@helper is used to define re-usable helper methods in view. For ex in your case you have defined the TestHelper to generate a <p> tag based on some condition so wherever you require <p> tag, you can call TestHelper method. While TagBuilder is used to create a new tag with a specified tag name. For example the below extension method used TagBuilder to generate an img input.

using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1.Helpers
{
    public static class ImageHelper
    {
        public static string Image(this HtmlHelper helper, string id, string url, string alternateText)
        {
            return Image(helper, id, url, alternateText, null);
        }

        public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
        {
            // Create tag builder
            var builder = new TagBuilder("img");

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

            // Add attributes
            builder.MergeAttribute("src", url);
            builder.MergeAttribute("alt", alternateText);
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

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

    }
}

Now to render you can define it as

@Html.Image("img1", <<Src of image>>, <<Name Of Image>>)

TagBuilder provides the capability of adding classes, merging attributes too. You can read about TagBulider here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM