How to write HtmlHelper in Fluent syntax

I have a simple tag constructor that looks like this:

public static MvcHtmlString Tag(this HtmlHelper helper, string tag, string content)
{
    var tagBuilder = new TagBuilder(tag){InnerHtml = content};
    return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.NormalTag));
}

And I can use it like this:

@Html.Tag("em", Model.Title)

which produces:

<em>The Title</em>

How can this be written to use Fluent Syntax, so it will look like this:

@Html.Tag("em").Content(Model.Title)
+4
source share
1 answer

You must define the interface and implementation of the linker. Hope my example can give some recommendations:

public static class MyHtmlExtensions
{
    public static IMyTagBuilder Tag(this HtmlHelper helper, string tag)
    {
        return new MyTagBuilder(tag);
    }
}

Then you define your interface and builder implementation:

public interface IMyTagBuilder : IHtmlString
{
    IHtmlString Content(string content);
}

public class MyTagBuilder : IMyTagBuilder
{
    private readonly TagBuilder _tagBuilder;

    public MyTagBuilder(string tag)
    {
        _tagBuilder = new TagBuilder(tag);
    }

    public IHtmlString Content(string content)
    {
        _tagBuilder.InnerHtml = content;
        return this;
    }

    public string ToHtmlString()
    {
        return _tagBuilder.ToString(TagRenderMode.NormalTag);
    }
}

Since it IMyTagBuilderimplements IHtmlString, it can be used either with a call .Content()or without it.

, , IFluentInterface, (ToString, Equals, GetHashCode GetType) IntelliSense, .

. API- Daniel Cazzulino Funq

+10

Source: https://habr.com/ru/post/1533589/


All Articles