Click here to Skip to main content
Click here to Skip to main content

Custom HTML Extensions for MVC3

, 19 Jun 2012
Rate this:
Please Sign up or sign in to vote.
This article demonstrates how we can create custom controls in MVC3.

Introduction

In this article, I am going to share my experience in creating HTML extensions for ASP.NET MVC3 Razor. At the end of the article, you will learn something new on how to create custom extension methods and its advantages. 

This is part one of two that I want to share with you.

Background 

This article is meant for an intermediate / experienced programmer who has some experience in developing applications in MVC3 Razor/ASPX.

There are two ways of creating HTML extensions:

  1. With Extension Methods
  2. Creating a cshtml file with all the logic. Either we can code with @helper or Razor and/or HTML. Then pre-compile it to generate a DLL.

With Extension Methods

These extensions are written from scratch extensively using code. Here’s a sample example of how you can create an HTML extension which outputs a Video tag for HTML5. You have to create a Class Library project. Create a static class say ViedoExtension and copy the below mentioned code.

If your browser supports HTML5, then you should be able to see a video tag, else you will see a message ‘Your browser doesn't support video tags'.

public static class VideoExtension
{
    public static MvcHtmlString Video
	(this HtmlHelper html, string src, bool showControls)
    {
        string url = UrlHelper.GenerateContentUrl(src, html.ViewContext.HttpContext);
        var tag = new TagBuilder("video") 
          {InnerHtml = "Your browser doesn't support video tags."};

        tag.MergeAttribute("src", url);
        if(showControls)
        // Show Play/Pause buttons
            tag.MergeAttribute("controls", "controls"); 
        return MvcHtmlString.Create(tag.ToString());
    }
}

With helper method 

Your cshtml either can have @helper or just a code with Razor syntax. Create a Class Library project and a new Razor cshtml file. Copy paste the below mentioned snippet for generating the list with <li>.

@helper WriteList(string[] items) 
{
     @foreach (var s in items)<ul>{
            <li> 
               @s  
            </li> 
}      </ul>}   

There is no way to reuse this cshtml unless you pre-compile this code to generate a DLL. We will next see how to re-compile the above one.

  1. Go to the VS Extension Gallery, it is under Tools in VS. Then install the Razor Single File Generator.

    MVC3CustomControl/razortocode.png

  2. Under the cshtml file -> Properties, set the Build Action to Content, and set the custom tool to MVCRazorClassGenerator.
  3. Compile the Class Library so that you will now see the *.cs file for the corresponding cshtml file under the cshtml file.
  4. Do some minor tweaks. Say renaming the class name of the *.cs file or extracting the core logic to a method.
  5. @{
        ViewBag.Title = "Sample code to demonstrate the usage of Custom Controls";
        var obj = new WriteToList();
        var str = new string[2]
                           {
                               "Test",
                                "Ranjan"
                           };
    } 
    @using (Html.BeginForm())
    {            
       @obj.WriteList(str)         
    }

Points of interest

It’s very interesting and fun to create an HTML extension method. I feel the second approach is really faster than the first one as we are more comfortable in writing cshtml. Wait for part two that I will be sharing with you soon.

Advantages  

Custom code in a library project makes it easy to produce a binary that can be used in multiple projects without having to keep the source files around.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile
 
Around 9 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.
 
In Brief
 
Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.
 
Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF
 
Software Development
 
Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI
 
Healthcare Domain Experience
 
CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability
 
Others:
 
TTD, BDD
 
Education
 
B.E (Computer Science)
 
CodeProject Contest So Far:
 
1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro
 
2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics
 
3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin
 
4. Intel App Innovation Contest 2013 - eHealthCare - http://www.codeproject.com/Articles/635815/eHealthCare
 
5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Content 2014

Comments and Discussions

 
GeneralMy vote of 1 PinmvpMarcus Kramer25-Jan-13 4:34 
Question[My vote of 1] OMG this is just aweful PinmvpSacha Barber14-Jun-12 21:49 
AnswerRe: [My vote of 1] OMG this is just aweful PinmemberRanjan.D19-Jun-12 15:34 
GeneralMy vote of 3 PinmemberVitaly Tomilov14-Jun-12 0:43 
GeneralRe: My vote of 3 PinmvpSacha Barber14-Jun-12 21:46 
QuestionModels PinmemberMauxel16-Apr-12 0:38 
AnswerRe: Models PinmemberSeishin#13-Jun-12 22:01 
QuestionHow To use server control like @HTML.Textbox Pinmembernageshwa18-Jan-12 23:55 
AnswerRe: How To use server control like @HTML.Textbox PinmemberSeishin#13-Jun-12 22:02 
GeneralRe: How To use server control like @HTML.Textbox PinmemberRanjan.D19-Jun-12 15:34 
QuestionTypo error PinmemberJamil Hallal18-Jul-11 1:49 
AnswerRe: Typo error PinmemberRanjan.D22-Jan-12 5:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 19 Jun 2012
Article Copyright 2011 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid