I’ve been upgrading an application to MVC 2 recently and I’m really liking a lot of the new features, so here’s some of my favourites:
Steve Sanderson’s xVal was great for adding client/server side validation to MVC 1 painlessly. Obviously someone at Microsoft liked it because now pretty much the exact same functionality is baked into MVC 2.
RequireHttps action filter
Want a single action or all actions of a controller to always use ssl? You used to have to code this up yourself but now you can just add the RequireHttps attribute to your class or method and, if it isn’t already, it’ll automatically be redirected to use ssl.
Strongly typed Html Helpers
I really dislike magic strings which meant that code like this:
<%= Html.TextBox("Name", Model.Name) %>
always felt wrong inside a view. Now you can use the the strongly typed helper methods instead and do this:
<%= Html.TextBoxFor(m => m.Name) %>
No magic string, so much nicer and obviously there are LabelFor, TextAreaFor etc. methods.
Html.EditorFor() and Html.DisplayFor()
Even better than strongly typed helpers is editor/display templates which lets you create your own views for editing and displaying different object types and then render them using the Html.EditorFor and Html.DisplayFor methods. It’s difficult to get across how awesome this is without writing a whole post about it, fortunately someone’s already done that for me and I can’t recommend it enough.
Simpler Http verb attributes
To specify that a controller action only accepted accepts a Post you used to have to use the following attribute:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id)
Now the attributes have been simplified so you can just do:
[HttpPost] public ActionResult Edit(int id)
Not a massive change, but it’s so much tidier and easier to read.