Creating custom html controls in mvc
I have been working with MVC, a lot playing around to make the pages more flexible and easier customization. We have several approaches to create a custom html controls.Here am simply demonstrating how to create a custom label control with HTML Extension.Please check out step by step below
Here i have taken a form with basic simple controls with fist name and last Name
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns= "http://www.w3.org/1999/xhtml "> <head id="Head1" runat="server"> <title>Index</title> </head> <body> <div> <% using (Html.BeginForm()) { %> <label for="firstName">First Name:</label> <br /> <%= Html.TextBox("firstName")%> <br /><br /> <label for="lastName">Last Name:</label> <br /> <%= Html.TextBox("lastName")%> <br /><br /> <input type="submit" value="Register" /> <% } %> 1 </div> </body> </html>I want to change the label in HTML label control, in order to do that we need to create html extension method
using System; using System.Web.Mvc; namespace MvcApplication1.Helpers { public static class LabelExtensions { public static string Label(this HtmlHelper helper, string target, string text) { return String.Format("<label for='{0}'>{1}</label>", target, text); } } }After creating the build you application successfully, Then you will extension method in Intellisense of visualstudio
Then See the code of custom label control
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index3.aspx.cs" Inherits="MvcApplication1.Views.Home.Index3" %> <%@ Import Namespace="MvcApplication1.Helpers" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Index3</title> </head> <body> <div> <% using (Html.BeginForm()) { %> <%= Html.Label("firstName", "First Name:") %> <br /> <%= Html.TextBox("firstName")%> <br /><br /> <%= Html.Label("lastName", "Last Name:") %> <br /> <%= Html.TextBox("lastName")%> <br /><br /> <input type="submit" value="Register" /> <% } %> </div> </body> </html>I hope this will help...
Labels:
MVC