Creating a Bootstrap Alert Tag Helper

To create a Bootstrap Alert Tag Helper, which will be a little bit more advanced than the previous example, follow these steps:

  1. Create a new class called BootstrapAlertTagHelper in the TagHelpers folder.
  2. Change the class to inherit from TagHelper.
  3. Add a Boolean property called Dismissable and a string property called Color to the class:
             public bool Dismissable { get; set; } 
            public string Color { get; set; } 
    
  4. Next, override the ProcessAsync method, as illustrated here:
            public override async Task ProcessAsync(TagHelperContext context, 
           TagHelperOutput output) 
            { 
                output.TagName = "div"; 
                output.Attributes.Add("class","alert alert-" + Color); 
                output.Attributes.Add("role", "attribute"); 
                if (Dismissable) 
                    output.PostContent.SetHtmlContent( 
                $"<button type="button" class="close" data-dismiss="alert">
                <span aria-hidden="true">&times;</span></button>"); 
     
                var content = await output.GetChildContentAsync(true); 
            } 
    

The preceding code will create a new <div> element and set its class to alert and alert-*, depending on the value set in the Color property. It will check whether the Dismissable property is set to true, and, if it is, call a <button> element to the end of the content using the PostContent.SetHtmlContent method.

Using the Bootstrap Alert Tag Helper

To use the Bootstrap Alert Tag Helper inside your view, use the following:

<div class="row"> 
   <bootstrap-alert color=" danger" dismissable="true"> 
       <strong>An error occurred</strong> Dismiss me to continue. 
   </bootstrap-alert> 
</div> 

The preceding helper code will generate a red/danger Bootstrap alert that is also dismissible. Any HTML content specified inside the helper will be rendered inside the Bootstrap Alert.

..................Content has been hidden....................

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