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:
- 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 );
- sb.Append("!");
- }
- else
- {
- sb.Append("Welcome");
- }
-
- sb.Append("</ol>");
- 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">
- @Html.LoginStatus("breadcrumb")
- </div>
- </div>
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