Wednesday, December 3, 2008

Automating - 7 Controller actions with Visual Studio templates

I am not big on repeating code or typing more than I have to. So, as I started adding entities to a RESTful API (which is built on .NET MVC) I quickly saw a need for automation. It seemed that I was almost always building out my controllers using the 7 standard actions (8 if you separate Delete and Destroy) that, say, a Rails application might automatically spin out - Index, Show, New, Edit, Create, Update, Delete and Destroy.

I wanted the elegance of the Rails controller code generation in a .NET application with out having to do much work - so I used Visual Studio templates to help me automate.

I wanted to produce this:


I began by building out a default controller exactly how I always do, with all of the actions, comments, etc...

Then I browsed to File Menu >> Export Template...


Select "Item template" and the project where the files is that you want to base your template on...


Choose the file (mine is the "PersonController")....


Choose the references (I rolled with System, System.Web, and System.Web.Mvc)...



Then set the name and description of the template...

Once you click finish, you're good to go...

Right Click on the folder where you want to create your new controller >> Add >> New Item...


You should be able to see your new template in the C# root (I moved mine from the root to C# >> Web >> MVC - by going to the templates directory and moving the new template zip into the proper folder).

That's it... now I am whipping out controllers for the API.

1 comment: