Custom User Control in ASP.NET MVC


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


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:

public static class LoginStatusControl  
    public static MvcHtmlString LoginStatus(this HtmlHelper htmlHelper, string CssClass)  
        StringBuilder sb = new StringBuilder();  
        sb.Append("<ol class='" + CssClass + "'>");  
        if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)  
            sb.Append("Hello ");  
            sb.Append(System.Web.HttpContext.Current.User.Identity.Name );  
        return MvcHtmlString.Create(sb.ToString());  

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.

<div class="row">  
    <div class="col-xs-3">  

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

Here is the screen.


Figure 1: Before Login

Figure 2: After Login


The following two tabs change content below.

Tom Mohan

Tom Mohan is a technologist who loves to code and build. He enjoys working on Microsoft Technologies. Tom specializes in ASP.NET MVC, Web API , Azure, C# ,WPF, SQL etc and holds a Bachelor engineering degree in Computer Science. Certification : MCSD , MCTS

Latest posts by Tom Mohan (see all)