To create a Bootstrap Alert Tag Helper, which will be a little bit more advanced than the previous example, follow these steps:
BootstrapAlertTagHelper
in the TagHelpers
folder.TagHelper
.Dismissable
and a string
property called Color
to the class:public bool Dismissable { get; set; } public string Color { get; set; }
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">×</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.
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.
18.218.212.102