Wednesday, July 20, 2011

Using Extension Methods in MVC

As many .Net developers have learned extension methods provide a mechanism to quickly add on capabilities to existing data types and methods.  If you are unfamilar with Extension Methods, Microsoft provides a great tutorial and documentation via MSDN (http://msdn.microsoft.com/en-us/library/bb383977.aspx). 

This particular post is related to utilizing these methods within MVC and the necessary work around for them to work with in your code.

Setup:

  1. Create your extension method as normal, and put your Class in a folder you created to house your extensions (typically done in the App_Code folder in ASP.Net web apps - this is not a folder that is an available system folder for MVC)
  2. Perform a build via the build menu or CTRL+SHIFT+ B
  3. Attempt to add the Using statement to the top of controller, data model, or class.
Why is my namespace not showing up?

Well, this is because in MVC by default the class is added with a build action of "Content".  This means that when you build the application it did not compile your extension method class.

So how do you fix this?

This actually extremely easy via the following:
  1. Right click on the extensions class file you created
  2. Select Properties
  3. The first option in properties window is Build Action
  4. Select Compile from the drop down
  5. Build the application
Your extension methods namespace should now be available to reference in any of the other classes, controllers, data models via the Using statement. From then on within that particular class you can use your extension method as normal.

*** All Content is provided As Is ***

2 comments: