Custom HTML User Control in ASP.Net MVC Razor View Engine

This article describes creation of a custom control using HtmlHelper in ASP.NET MVC 5 and the Razor view engine.

Scope

This article describes creation of a custom control using HtmlHelper in ASP.NET MVC 5 and the Razor view engine.

Introduction

In ASP.NET we create user controls as .ascx files. But in ASP.NET MVC it is a little bit different. In MVC we have multiple ways to do it. We have partial views, HtmlHelper and so on. HtmlHelper is a class for rendering HTML controls in a view.

Here I'm demonstrating a very simple login status HTML user control. For this I have created one static class and a static method as in the following:

  1. public static class LoginStatusControl  
  2. {  
  3.   
  4.     public static MvcHtmlString LoginStatus(this HtmlHelper htmlHelper, string CssClass)  
  5.     {  
  6.         StringBuilder sb = new StringBuilder();  
  7.         sb.Append("<ol class='" + CssClass + "'>");  
  8.         if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)  
  9.         {  
  10.             sb.Append("Hello ");  
  11.             sb.Append(System.Web.HttpContext.Current.User.Identity.Name );  
  12.             sb.Append("!");  
  13.         }  
  14.         else  
  15.         {  
  16.             sb.Append("Welcome");  
  17.         }  
  18.           
  19.         sb.Append("</ol>");  
  20.         return MvcHtmlString.Create(sb.ToString());  
  21.     }  

Here we will pass the CSS class to our control. If the user is authentic then it will show, for example, ”Hello Tom !“. Otherwise only the welcome message will be displayed. Then I have implemented this control in my layout.

  1. <div class="row">  
  2.     <div class="col-xs-3">  
  3.         @Html.LoginStatus("breadcrumb")  
  4.     </div>  
  5. </div> 

Here “breadcrumb” is the CSS class. We can pass any parameters to the user control, like a method.

Here is the screen.

Before Login
                                                            Figure 1: Before Login

After Login
                                                            Figure 2: After Login