Posts
208
Comments
1144
Trackbacks
51
Create Your Own Code Snippets in Visual Studio 2010 for MVC 2

One of the great new features in Visual Studio 2010 is the ability to now use code snippets inside of ASP.NET, HTML, and JavaScript files. Snippets have long been a productivity boost for regular C# code but have been sorely missing for mark up. In fact, frameworks like MVC 2 actually ship with their own snippets.

 

There are only about 10-15 snippets that are currently shipping with MVC (and many of those are just duplicated because there are both VB and C# versions).  That doesn’t seem like very many.  But let’s have a look at one that would be pretty common – the HTML helper for a text box:

That snippet produces the following code:

   1:  <%= Html.TextBox("FirstName") %>

Hmmm. That code doesn’t seem very “MVC2ish”.  First off, it’s using the old school double-quoted string to specify the property rather than the new strongly-typed lambda-based HTML helper. Secondly, it’s using the TextBox() method rather than the EditorFor() method.  Third, it’s using the old <%= syntax which Microsoft is trying to get us to forget exists, rather than the new <%: HTML encoding syntax.

The best approach here is for us to create our own snippets customized to our heart’s content. But the snippet files are not the easiest things to work with so rather than starting from scratch, let’s just grab the MVC textbox snippet and modify it. The snippets can be found in the directory: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Visual Studio 2010\Snippets\HTML\1033\ASP.NET MVC 2. I’m going to grab the “textboxmvc.snippet” file from there, create a directory called “My MVC2 Snippets” and put it inside of the normal code snippets directory structure for Visual Studio. So the full path will be: <My Documents>\Visual Studio 2010\Code Snippets\Visual Web Developer\My MVC2 Snippets. Then I’ll rename “textboxmvc.snippet” to “editorfor.snippet”.

In order to get Visual Studio to recognize this location, I need to do Tools –> Code Snippet Manager and select the directory:

Next I’ll open the editorfor.snippet file in any code editor and change a few key lines:

   1:  <CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
   2:    <Header>
   3:      <Title>editorfor</Title>
   4:      <Author>Steve Michelotti</Author>
   5:      <Shortcut>editorfor</Shortcut>
   6:      <Description>Markup snippet for an ASP.NET MVC EditorFor helper</Description>
   7:      <SnippetTypes>
   8:        <SnippetType>Expansion</SnippetType>
   9:      </SnippetTypes>
  10:      <ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325}</ProjectTypeGuids>
  11:    </Header>
  12:    <Snippet>
  13:      <Declarations>
  14:        <Literal>
  15:          <ID>property</ID>
  16:          <ToolTip>property</ToolTip>
  17:          <Default>property</Default>
  18:        </Literal>
  19:      </Declarations>
  20:      <Code Language="html" Key="*"><![CDATA[<%: Html.EditorFor(m => m$property$) %>$end$]]></Code>
  21:    </Snippet>
  22:  </CodeSnippet>

Line 3, 4, 5, and 6 are simple and straight-forward replacements.  The primary line I need to change is line 20. I’m going to use the generic “m” (for “Model”) for my lambda identifier and then use a replacement variable called $property$ (which I also specify on lines 15-17). I intentionally left out the “.” because after the snippet expands, I want the next keystroke I press to be the “.” so that intellisense will naturally come up for me (this snippet can be expanded without the mouse by typing “<edi”):

 

Just hit <Enter> and you’re all done!

Snippets are an area that you should absolutely leverage to take care of your most common mundane coding tasks and customize them per your own personal preferences/standards. Historically, my tool of choice for editing/creating snippet files is Snippy (though this doesn’t appear to actively be under development any more). I’ve also used Snippet Designer which has nice integration with Visual Studio. It appears that neither of these tools (yet) have support for the new language=”html” that is new in VS2010 (hopefully will support soon).

posted on Tuesday, February 16, 2010 2:00 AM Print
Comments
Gravatar
# re: Create Your Own Code Snippets in Visual Studio 2010 for MVC 2
Tyler
2/16/2010 3:20 PM
Very cool. I've also found this useful:

<%= Html.SuperValidTextBoxFor(m => m.MyProp)%>

and here's the simple extensions:

public static MvcHtmlString SuperValidTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
MvcHtmlString label = html.LabelFor(expression);
MvcHtmlString txbox = html.TextBoxFor(expression);
MvcHtmlString valid = html.ValidationMessageFor(expression);
return label.Join(" ", txbox, valid);
}

public static MvcHtmlString Join(this MvcHtmlString mvc, string separator, bool singleLine, params MvcHtmlString[] parts)
{
StringBuilder sb = new StringBuilder();
if (singleLine)
sb.Append(mvc.ToString() + separator);
else
sb.AppendLine(mvc.ToString() + separator);

foreach (var p in parts)
{
if (singleLine)
sb.Append(p.ToString() + separator);
else
sb.AppendLine(p.ToString() + separator);
}
return MvcHtmlString.Create(sb.ToString().TrimEnd(separator.ToCharArray()));
}

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud