Wednesday, October 12, 2011

Create Custom Controls in MVC3


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

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


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 Custom Controls

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.

Create Controls with Extension methods:

These are the controls written from the scratch extensively using code. Here’s one sample example of how to create a control which outputs a Video tag for HTML5. First you need to create a ClassLibrary project then create a static class say ViedoExtension. Copy the below mentioned code.

If your browser is supporting HTML5 then you should be able to see a video tag else you will see a message ‘Your browser does’nt support video tags.

public static class ViedoExtension {    
public static MvcHtmlString Video(this HtmlHelper html, string src,
bool showControls)
{ string url = UrlHelper.GenerateContentUrl(src,
var tag = new TagBuilder("video"){InnerHtml = "Your browser
doesn't support video tags."
tag.MergeAttribute("src", url);
// Show Play/Pause buttons
tag.MergeAttribute("controls", "controls");
return MvcHtmlString.Create(tag.ToString());

The static method of Video method returns an encoded string, so do not have to encode it again while using this extension. Here’s the usage in your web application: @Html.Video(“cat.avi”,true)


Anonymous said...

Thanks for finally writing about > "Create Custom Controls in MVC3"
< Liked it!

Feel free to visit my weblog :: Minecraft Lets Play

Anonymous said...

I'm not sure why but this web site is loading incredibly slow for me. Is anyone else having this problem or is it a issue on my end? I'll check back later and
see if the problem still exists.

Here is my site ... Mindcrack Lets Play

Anonymous said...

This design is spectacular! You certainly know how to keep a
reader entertained. Between your wit and your videos, I was
almost moved to start my own blog (well, almost...HaHa!) Wonderful job.
I really enjoyed what you had to say, and more than that, how you presented it.
Too cool!

Also visit my webpage ... Gameplay

Anonymous said...

This is a topic that's near to my heart... Many thanks! Where are your contact details though?

Here is my site Minecraft Gameplay

Anonymous said...

Thanks for finally writing about > "Create Custom Controls in MVC3" < Liked it!

Here is my web-site Minecraft Wireless Redstone