Category: MVC

Real World MVC 3 Development

During the last couple of months I have been working with MVC 3 daily and I have used Nuget packages and tools which have helped in a number of areas, in this post I will give a shout out to these tools which help make MVC 3 a pleasure to work with. For the most part Nuget packages can be found for these tools so you can add them very easily and get going quickly.

Routing

    • Attribute routing for MVC – Remove any routing concerns/issues and start using this now.
    • T4MVC helps make your MVC code much more maintainable, enough said.

Page Performace

      • Chirpy is an open source Visual Studio Add In For Handling JavaScript, Css, DotLess, and T4 Files, which in essence improves page performance.
      • Cassette – Cassette automatically sorts, concatenates, minifies, caches and versions all your JavaScript, CoffeeScript, CSS, LESS and HTML templates.

Profiling

      • Mvc Mini Profiler – A simple but effective mini-profiler for ASP.NET MVC and ASP.NET.
      • Glimpse – What Firebug is for the client, Glimpse does for the server… in other words, a client side Glimpse into whats going on in your server.

Error Logging

      • ELMAH – ELMAH (Error Logging Modules and Handlers) is an application wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment

All MVC posts

        • All of my MVC blog posts can be found here.

Conclusion

MVC is great to work with on its own but these tools can only enhance the development process. Please leave feedback or comments, and also let me know if I have missed out on any tools which I can add to this list.



MVC – get some help

If you’re using MVC and you’re looking for some in-depth information on basically whats going on when you run the code then you should take a look at Miniprofiler (from the guys at StackOverflow) or Glimpse.


Miniprofiler can be added in to your solution and can give you all sorts of really useful information such as which view is currently being rendered and from which method in the controller (which is not always obvious). this can be quite a time saver if you’re not used to the codebase and just want to quickly find the ActionResult which has been hit.

To Add MiniProfiler to an MVC application install it using the Nuget Package Manager console. (you need to use the console sometimes if the package uses a Powershell script)

Once added via Nuget browse to your global.asax file and add in the following 2 methods:-

[sourcecode language=”csharp”] protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Start();
}
}
[/sourcecode]

and then :-

[sourcecode language=”csharp”] protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
[/sourcecode]

Rebuild your code and run your application and you’ll see info being displayed by MiniProfiler in the top left hand corner as follows:-

Glimpse


Glimpse is a JavaScript plug-in which informs you of information such as Route Debugging which is a superb feature. Add Glimpse via Nuget and then browse to your site and add /glimpse.axd to the end of the url from your application:-

Glimpse

Pres enter and you’ll be taken to this screen, this nice bit here is you can drag the ‘Turn Glimpse On’ and ‘Turn Glimpse Off’ to your fav bar and just click them to do as it says on your site. (This is all done in JavaScript and has very little overhead)

Glimpse

After clicking on ‘Turn Glimpse On’ we see the little eyeball bottom right of the screen:-

Glimpse

When clicking on that you’ll see something like the following:-

Glimpse
Here we can drill into all sorts of information such as:-

  • What route has been called
  • Which view has been rendered
  • Time spent to render the page and timings for each part
  • Config on the server

Again go get them and you’ll have them up and running very quickly and benefit from the features they come with.



AttributeRouting for MVC

AttributeRouting is a fantastic open source Nuget package which allows you to specify routes using attributes on your MVC controllers and actions. We use it in all of our MVC projects at work and I highly recommended it, saves you having to map all y.

Attribute Routing

The QuickStart Guide can be found here.

Main reasons to use AttributeRouting

•Decorate your actions with GET, POST, PUT, DELETE, and verb agnostic attributes.
•Map multiple routes to a single action, ordering them with an Order property.
•Specify route defaults and constraints inline and also using attributes.
•Specify optional params inline with a token before or after the parameter name.
•Specify the route name for supporting named routes.
•Define MVC areas on a controller or base controller.
•Group or nest your routes together using route prefixes applied to a controller or base controller.
•Support legacy urls.
•Set the precedence of routes among the routes defined for an action, within a controller, and among controllers and base controllers.
•Generate lowercase outbound urls automatically.
•Define your own custom route conventions and apply them on a controller to generate the routes for actions within the controller without boilerplate attributes (think RESTful style).
•Debug your routes using a supplied HttpHandler.

Go check it out you wont be disappointed.



Chirpy for MVC

Chirpy is an open source Visual Studio Add In For Handling JavaScript, Css, DotLess, and T4 Files.

Better Page Performance
When you validate your site against YSlow it gives you reports on why your webpages may take some time to render in the browser – Chirpy can help with this big time by minifying script files like javascript, css and more so that there are less requests made to the server on each page request – better page performance is always good.

YSlow

The full list of what Chirpy can do can be found here.



T4MVC for MVC

If your using MVC then please at least take a look at T4MVC or better still add it to your project from Nuget here T4MVC from Nuget – It’s written by David Ebbo who works for Microsoft and works on Nuget as well as a lot of other cool stuff.

What is T4MVC? – the following is lifted from the documentation:-

“T4MVC is a T4 template for ASP.NET MVC apps that creates strongly typed helpers that eliminate the use of literal strings when referring the controllers, actions and views. It helps make your MVC code much more maintainable, and gives you intellisense where you normally would not have any.”

Some links for more info:-

  • David’s Blog posts on T4MVC can be found here:- Posts
  • T4MVC Introduction Video here.

An example again lifted from the site would be:-

[sourcecode language=”csharp”] @Html.RenderPartial("DinnerForm");
[/sourcecode]

Now becomes

[sourcecode language=”csharp”] @Html.RenderPartial(MVC.Dinners.Views.DinnerForm);
[/sourcecode]

and you get Intellisense for free which is nice.

Also this

[sourcecode language=”csharp”] @Html.ActionLink("Delete Dinner", "Delete", "Dinners", new { id = Model.DinnerID }, null)
[/sourcecode]

becomes this

[sourcecode language=”csharp”] @Html.ActionLink("Delete Dinner", MVC.Dinners.Delete(Model.DinnerID))
[/sourcecode]

The beauty of this needs to be tried to ge the full extent of whats available but its really easy to add in and change your links in a flash.

By the way it even works for images so heres an example using the aspx syntax.

[sourcecode language=”csharp”] <img src="/Content/nerd.jpg" />
[/sourcecode]

becomes

[sourcecode language=”csharp”] <img src="<%= Links.Content.nerd_jpg %>" />
[/sourcecode]

T4MVC is very handy indeed and you should definitely check this out.



Using MvcSitemap – for generating website breadcrumbs – Part 1

Over the last 2-3 weeks I was looking at implementing breadcrumbs on an MVC 3 website for navigation purposes and I highly recommend using the mvcsitemap provider written by Maarten Balliauw which can be found here and you can read more about his Nuget Package for it Nuget Package.

To try out the MvcSiteMap follow these steps:-

  1. Start Visual Studio and choose a new MVC 3 application.
  2. Image1

  3. Once that’s done open up the Nuget Package Manager Console and add the Nuget package called mvcsitemapprovider.
  4. Nuget

  5. Now we have added the Nuget package you will see that a file called Mvc.sitemap has been added to the root of the solution.
  6. Image3

  7. Now we want to add some content to the MVC.sitemap file, lets add some content now :-
  8. [sourcecode language=”xml”] <?xml version="1.0" encoding="utf-8" ?>
    <mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&quot;
    xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0&quot;
    xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0 MvcSiteMapSchema.xsd"
    enableLocalization="true">
    <mvcSiteMapNode title="Home" controller="Home" action="Index">
    <mvcSiteMapNode title="About" controller="Home" action="About" />
    <mvcSiteMapNode title="ContactUs" controller="ContactUs" action="Index">
    <mvcSiteMapNode title="By Phone" controller="ContactUs" action="Phone"/>
    <mvcSiteMapNode title="By Email" controller="ContactUs" action="Email"/>
    </mvcSiteMapNode>
    </mvcSiteMapNode>
    </mvcSiteMap>

    [/sourcecode]
  9. Ok so now we need to add in a ContactUsController and add the extra 2 ActionResults
  10. [sourcecode language=”csharp”] public ActionResult Phone()
    {
    return View();
    }

    public ActionResult Email()
    {
    return View();
    }
    [/sourcecode]

  11. Last but not least in order to show the breadcrumbs on a webpage just add the following code to your view
  12. [sourcecode language=”csharp”] @Html.MvcSiteMap().SiteMapPath()
    [/sourcecode]

Now we have the most basic of breadcrumbs working off of our Mvc.sitemap xml file, The next blog entry will cover more complex sitemap which uses a dynamic node provider to generate the nodes dynamically when first called – enjoy.



MVC 3 useful Tools

Having be doing some MVC 3 work recently I have used the following tools and I highly recommend every one of them if you are doing this type of work.

  • Mvc Mini Profiler – A simple but effective mini-profiler for ASP.NET MVC and ASP.NET.
  • Glimpse – What Firebug is for the client, Glimpse does for the server… in other words, a client side Glimpse into whats going on in your server.
  • Cassette – Cassette automatically sorts, concatenates, minifies, caches and versions all your JavaScript, CoffeeScript, CSS, LESS and HTML templates.
  • ELMAH – ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment

Please take a little bit of time to look at each of these tools – they are all free and are fantastic.



Converting MVC2 app to MVC3 (webform to Razor syntax)

I have been upgrading an MVC 2 web application (which used the web form view) to an MVC 3 (razor syntax) application and have noted a few things I came across and if this can help anyone then thats always nice. I havent went into the dll changes and any web.config changes required to update the app from MVC 2 to MVC 3 – this is more a post about syntax changes I ran into.

The old code looked like this:-
[sourcecode language=”csharp”] <%= Html.Pager((IPagination)Model)%>
[/sourcecode]

with razor you may see the html being displayed rather than the correct code, to fix this we need to use the Html.Raw() helper which takes a string as follows:-
[sourcecode language=”csharp”] @Html.Raw(Html.Pager((IPagination)Model).ToString())
[/sourcecode]

Another issue I ran into was that Razor automatically encodes all HTMl and this means that to get my HtmlHelpers working I had t make a very minor change. Thw webform syntax would have been as follows:-
[sourcecode language=”csharp”] public static string DatePicker(this HtmlHelper helper, string name)
{
return helper.DatePicker(name, null);
}

public static string DatePicker(this HtmlHelper helper, string name, string imageUrl)
{
return helper.DatePicker(name, imageUrl, null);
}

public static string DatePicker(this HtmlHelper helper, string name, object date)
{
return helper.DatePicker(name, "/Content/Images/calendar.gif", date);
}

public static string DatePicker(this HtmlHelper helper, string name, string imageUrl, object date)
{
var html = new StringBuilder();
….
….
….
return html.ToString();
}
[/sourcecode]

With Razor syntax this changes to return MvcHtmlString as below:-
[sourcecode language=”csharp”] public static MvcHtmlString DatePicker(this HtmlHelper helper, string name)
{
return helper.DatePicker(name, null);
}

public static MvcHtmlString DatePicker(this HtmlHelper helper, string name, string imageUrl)
{
return helper.DatePicker(name, imageUrl, null);
}

public static MvcHtmlString DatePicker(this HtmlHelper helper, string name, object date)
{
return helper.DatePicker(name, "/Content/Images/calendar.gif", date);
}

public static MvcHtmlString DatePicker(this HtmlHelper helper, string name, string imageUrl, object date)
{
var html = new StringBuilder();
….
….
….
return MvcHtmlString.Create(html.ToString());
}
[/sourcecode]

Hopefully this may come in handy for someone who comes across these items that require changing – I’ll post more if I come across them.



MVC Glimpse via NuGet

Glimpse is basically FireBug for MVC applications and it is written entirely using JavaScript – if you havent checked it out and you’re using MVC at all then please check this out asap.

It takes 30 seconds to install and have running on your application, it shows you details about everything that’s happening on the server, less talking go get it now!

Click —-> to Download Glimpse now.

Enjoy!



Modernizr MVC 3 update and what is modernizr?

If your using MVC 3 and you have updated to the latest update just after MIX 11 then you may notice a very nice addition to the Scripts folder, something called Modernizr, at the moment my brand new MVC 3 web app has modernizr-1.7.js included.

If you wanna know what Modernizr is –> modernizr ?

Follow @Modernizer on twitter and even watch Scott Hanselman talk about it at Mix 11 Modernizer at Mix (Scroll to about 11 minutes in)