Creating self-closing helpers

Self-closing helpers are helpers that can contain HTML and Razor markup. The built-in @Html.BeginForm() helper is an example of this helper type.

In order to create this type of HTML Helper, we'll need to create a helper class that implements the IDisposable interface. Using the IDisposable interface, we can write the element's closing tags when the object is disposed.

The Bootstrap Alert component is a good candidate for such a helper. To create the helper, we'll have to complete the following steps:

  1. Create a new subfolder called Alerts inside the Helpers folder in your project.
  2. Open the Enums.cs file and add a new item called AlertStyle:
            public enum AlertStyle 
            { 
                Default, 
                Primary, 
                Success, 
                Info, 
                Warning, 
                Danger 
            } 
    
  3. Add a new class file called Alert.cs to the Alerts folder.
  4. Add a new private, read-only TextWriter object field to the class called _writer:
            private readonly TextWriter _writer; 
    
  5. Create a constructor for the Alert class that accepts three parameters. The first is a reference to the IHtmlHelper interface, the second specifies the title of the alert, and the third indicates the style of the alert.
  6. Add the following code to the Alert class's constructor method:
            public Alert(IHtmlHelper helper, string title, 
            Enums.AlertStyle style = Enums.AlertStyle.Success) 
            { 
                _writer = helper.ViewContext.Writer; 
                var alertDiv = new TagBuilder("div"); 
                alertDiv.AddCssClass("alert"); 
                alertDiv.AddCssClass("alert-" + style.ToString().ToLower()); 
                alertDiv.Attributes.Add("role", "alert"); 
                alertDiv.TagRenderMode = TagRenderMode.StartTag; 
                var strong = new TagBuilder("strong"); 
                strong.InnerHtml.Append(title); 
                string html = ToString(alertDiv) + ToString(strong); 
                _writer.Write(html); 
            } 
    

In this code, we've set the _writer field to the Writer property of the IHtmlHelper interface's ViewContext property. By utilizing this property, we'll be able to write HTML to the current view.

We then built up the alert element's HTML markup using the TagBuilder object, and finally, sent the result to the _writer object to output. Note that we used a method called the ToString method in order to output the TagBuilder to a string. The code for the ToString method is as follows:

public static string ToString(Microsoft.AspNetCore.Html.IHtmlContent content) 
{ 
    var writer = new System.IO.StringWriter(); 
    content.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default); 
    return writer.ToString(); 
} 

The <div> element with the class name alert will be closed in the Alert class's Dispose method, which is implemented in the following manner:

public void Dispose() 
{ 
    _writer.Write("</div>"); 
} 

Next, add a new file called AlertHelper.cs to the HelpersAlerts folder.

Add the following code to the AlertHelper class: 
public static class AlertHelper 
{ 
    public static Alert Alert(this IHtmlHelper html, string title, Enums.AlertStyle style = Enums.AlertStyle.Success) 
    { 
        return new Alert(html, title, style); 
    } 
} 

Using the self-closing helper in a view

To use the helper we created earlier in our view, we'll use the C# using keyword. The using keyword restricts the scope of an object and works well with the IDisposable interface. In essence, as soon as the helper has finished rendering its HTML output, the Dispose method will automatically be invoked, thus closing the last <div> element tag.

To use the helper in a view, use the following markup:

@using Chapter5.Helpers.Alerts 
<div class="row"> 
    @using (Html.Alert("Title", Enums.AlertStyle.Success)) 
    { 
        <p>Hello World</p> 
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> 
    } 
</div> 

The helper will generate the required HTML in order to show the following panel in the browser:

Using the self-closing helper in a view
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.37.191