Archive for the ‘ASP .NET MVC’ Category

Consistent validation with ASP .NET MVC and jQuery

Saturday, March 6th, 2010

Recently I have been developing a couple of small web applications with version 1 of ASP .NET MVC, using jQuery’s validation plugin to provide a better client-side experience. As some of you may be aware, the validation features in the first release of MVC were sparse, although Phil and the team have certainly corrected this with the recent second version.

One aim I had with my validation features was to deliver consistent behaviour and appearance between client and server, so that users would get the same experience whether they had scripting turned on or off. It proved a little awkward at first, but I got there in the end, so thought I would post the results to my blog in case anyone else is trying to do the same.

When creating a strongly-typed view, MVC provides templates for common scenarios, e.g. Create, Edit, Details and so on. This gives the developer a head start and removes the need for a lot of monotonous coding. The server-side markup it generates for each field in the Create and Edit views is similar to the following

<label for="FirstName">FirstName:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName")

As you can see, each property of the model (in this case, the first name of a person) gets a label, an input control for editing its value, and any validation messages linked to the field are shown next to it. When this is rendered to the client, we get HTML like this

<label for="FirstName">FirstName:</label>
<input class="input-validation-error" id="FirstName" name="FirstName" type="text" value="" />
<span class="field-validation-error">First name must be entered.</span>

Whilst jQuery’s validation provides similar results straight out of the box, it’s not quite what I need. For starters, it uses a label to show the error message, whereas MVC uses a span. This is easily corrected by using the errorElement option of the plugin. So the script for the validator now looks like this

$().ready(function() {
  $('form').validate({
      errorElement: 'span',
      rules: { FirstName: { required: true } },
      messages: { FirstName: { required: 'Please enter the first name.' } }
  });
});

However that left me with a tricky problem – the input and error elements don’t have the correct classes attached to them, so the styling rules are not being applied. As you can see from the earlier markup, MVC applies the field-validation-error class to the element containing the error message, and the input-validation-error class to the element containing the invalid value. This is different to the jQuery plugin, which applies the error class to both elements.

Initially I tried playing around with the errorClass option, but could only get one or other of the correct classes applied. In the end I used the highlight and unhighlight functions, which are called when an error message is shown or hidden, respectively. By default, highlight adds the errorClass to the input element, and also removes the validClass. The validClass (valid by default) allows you to style the element to indicate that it contains valid input. My custom implementation of highlight continues to do this, but adds another couple of lines to apply the correct classes to the input element and the error message span. The JavaScript looks like this

highlight: function(element, errorClass, validClass) {
  $(element).addClass(errorClass).removeClass(validClass);
  $(element).addClass('input-validation-error');
  $(element.form).find('span[for=' + element.id + ']')
    .addClass('field-validation-error');}

The unhighlight function just does the reverse; I’ve omitted it for the sake of brevity here. I’ve been using this code for a while now and it seems to have had the desired effect. This is a great example of how flexible many of jQuery’s plugins are, as well as providing excellent functionality out of the box.

The sample code for this is available here, I’ve also included a slight change which ensures the validClass is applied correctly if you are targeting styles for it.

See also: jQuery validation advanced options, jQuery validation home

Plugging ELMAH into ASP .NET MVC

Friday, January 22nd, 2010

Over the past year or so ELMAH has becoming increasingly popular, and it’s not hard to see why. It has an excellent set of error logging and reporting features, doesn’t need to be referenced directly in any application code and is simple to configure.

Recently a troublesome ASP .NET application came into my care and I decided the first course of action was to plug ELMAH in. At the most basic level, this involves dropping the ELMAH dll into bin and a few changes to web.config; Scott Hanselman shows you how to do this on his blog.

However, because the app was built using ASP .NET MVC, its default HandleError attribute was intercepting all exceptions thrown by controllers, before ELMAH could got a look at them. As a result not all exceptions were being logged. To counter this, I created a custom version of the HandleError attribute, called ElmahHandleErrorAttribute. Well actually, Atif Aziz, author of ELMAH did, in a post on Stack Overflow, I just copied it!

The last piece of the puzzle is to create a base controller, from which all controllers in the application inherit, and apply the ElmahHandleErrorAttribute to it. Now all exceptions in the application will pass through the ELMAH pipleine.

It’s important to test that any custom error pages are also shown after ELMAH has done its bit. To do so, switch customErrors in web.config to on so that those pages are shown in preference to the traditional yellow screen of death (more information on customErrors can be found at MSDN). If you have error pages specific to particular HTTP error codes (i.e. one for 404s and one for the rest) then add these now.

Next, do something that is guaranteed to throw an exception in the app. Most of the time a typo in the connection string, if using a database, is a simple but effective way of doing this. Afterwards, ELMAH will have logged the exception (go to /elmah.axd to check) and the friendly error page will be rendered.

The reason I suggest testing these pages is that when developing locally, most of us run with customErrors off so we get the YSOD in all its glory, stack trace and all – and so we should. As a result, if there are any issues with custom error pages not being shown correctly, they often only come out during formal testing, at which point it is often more time consuming to fix.

I’ve tripped over this myself a couple of times, particularly if the custom error page accesses the database. Imagine a situation in which the database is offline, and an exception is thrown. ELMAH logs the details, and ASP .NET MVC tries to render the custom error page, at which point another attempt is made to connect to the database! The custom error page will then blow up – not good at all.

The lesson here is that custom error pages should be as basic as possible. If they use the same master page as the rest of the app, and that master page shows a database value somewhere in the header or footer (e.g. friendly name of the current user, which is quite common), they are vulnerable to this problem. Far better to have a separate master page for all error pages which uses the same styles as the rest of the site but consists of plain, basic markup.

One last point to make is that ELMAH isn’t just for web apps, although it works best there. I recently worked on a solution that had a web front end and a console application for pumping data into the database. I made use of ELMAH in both apps, thereby having a central repository for all exception information. I’ve pointed my feed reader at ELMAH’s RSS feed (/elmah.axd/rss) and am notified as soon as any part of the solution experiences an error.

So, if you’re not yet on board the ELMAH bandwagon, now is the time to join in.

Custom routing for ASP .NET MVC

Monday, May 26th, 2008

Custom routing for ASP .NET MVC

Those familiar with the MVC framework for ASP .NET will know that one of its primary features is the mapping of URLs to methods on controllers. For example, /Products/Find will cause the ProductsController to be created and have its Find method invoked. It is also possible to pass arguments to methods, for instance /Products/Load/53 would call the Load method of the ProductsController, supplying 53 as the argument.

Organising controllers

Whilst this allows the developer to structure their code better, keeping presentational logic in the view and application logic in the controller, it isn’t ideal. To continue the example, as the project grows it will provide an increasing amount of features related to products, all of which will be delivered by the ProductsController. As a result the code for searching for products will end up in the same class as that used to edit products, and so on.

Everyone has their own take on the MVC pattern and in the past I have tended to use one controller per use case. The use cases in question here are Find Product and Edit Product and as such their functionality would be provided by the FindProductController and EditProductController, rather than living together in a single ProductsController.

A simple way to implement this pattern is to keep the ProductsController and have it delegate all its work. For example, the Load method would simply create an instance of EditProductController and call its Load method, passing any arguments as well. Whilst this is feasible it is more of a workaround than a genuine solution. It would be far better to cut out the ProductsController altogether, and have methods on the two controllers be called directly. The routing engine in ASP .NET MVC is very flexible and, by developing a custom route, it is possible to do this.

Creating a custom route

It is the job of a route to take a URL and call the appropriate method of a controller. The default MVC route has a format of {controller}/{action}/{id}, however our use case route will use {useCaseNoun}/{useCaseVerb}/{action}/{id}. The key difference is that the controller token has been replaced with two new tokens, noun and verb. This will allow us to provide the following routes

URL Controller Action Behaviour
/Product/Find/Search FindProductController Search Execute a search for products and display the results
/Product/Find/Clear FindProductController Clear Reset all the fields of the search page
/Product/Find FindProductController [default] Execute the default controller method (more on this shortly)
/Product/Edit/Load/17 EditProductController Load(17) Load the product with ID 17 and display its data for editing
/Product/Edit/Save/23 EditProductController Save(23) Save the supplied data against the product with ID 23
/Product/Edit/Clear EditProductController Clear Clear out the edit page ready for entering a new product

A fringe benefit of adopting this strategy is that both controllers can have a method of the same name, e.g. Clear, but have the method perform a completely different task. With a single ProductsController there could only be one Clear method.

In order to register the custom route with the MVC framework, some changes need to be made to the Global.asax file. Its Application_Start method calls RegisterRoutes which, using the default MVC project template, will already set up the default route format of {controller}/{action}/{id}. To this method we need to add the following

routes.Add(new Route("{useCaseNoun}/{useCaseVerb}/{action}/{id}", new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(new { action = "Index", id = "" }),
});

Note that the default action is Index so, in the case of the /Product/Find URL in the table above, this would map to the Index method of the FindProductController.

At this point we can use Phil Haack‘s Url Routing Debugger to test that our URLs are being correctly routed. To do so we get a reference to Phil’s RouteDebug.dll and add the following code after RegisterRoutes is called

RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);

It is then possible to enter each of URLs into a browser and see which route they match. Check out Phil’s post for further details.

Creating a handler for the route

The format of our route is such that the {controller} token is no longer present. As a result the MvcRouteHandler that is associated with the route will not be able to identify which controller to use. Typically it just extracts the value of the controller token, appends “Controller” to it, and instantiates an object of that type. To resolve this issue we need to replace MvcRouteHandler with a route handler of our own.

Fredrik Normén produced an excellent blog post, Create your own IRouteHandler, which describes how to do this. For our route, we need to create two new classes, the first of which implements IRouteHandler, as shown below

public class UseCaseRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new UseCaseMvcHandler(requestContext);
    }
}

This class, UseCaseRouteHandler, is used in place of MvcRouteHandler, and simply creates a new IHttpHandler which will do the real work. The implementation of IHttpHandler is actually our second class, UseCaseMvcHandler. This inherits from MvcHandler and overrides the ProcessRequest method, during which the correct controller is identified and then created. It is this behaviour that we need to redefine.

To determine how our ProcessRequest should work, I downloaded the source code of the MVC framework itself, which is available from CodePlex. A quick inspection of MvcHandler‘s ProcessRequest shows that the GetRequiredString method is used to extract the values of the route’s tokens. For the default routing this is just a case of getting the controller name, whereas our custom route needs to grab both the {useCaseNoun} and {useCaseVerb} tokens. I moved this logic into a separate function, GetControllerName, which is shown below

private string GetControllerName()
{
    string noun = this.RequestContext.RouteData.GetRequiredString("useCaseNoun");
    string verb = this.RequestContext.RouteData.GetRequiredString("useCaseVerb");
    return verb + noun;
}

So, if the URL is /Product/Find/Search, this method will extract a noun of “Product”, a verb of “Find” and return the value “FindProduct”.

I then copied MvcHandler’s ProcessRequest code into UseCaseMvcHandler and replaced the line extracting the controller token value with a call to the GetControllerName function. Simple. Well, almost! Unfortunately the resource strings are not available to inheriting classes, and neither is the ControllerBuilder property. I replaced the former with a hard-wired string, whilst the latter is accessible via the ControllerBuilder class’ static Current property.

At this point the code is almost ready to run. We just need to adjust the code in RegisterRoutes so that our route uses the new UseCaseRouteHandler class. This is done as follows

routes.Add(new Route("{useCaseNoun}/{useCaseVerb}/{action}/{id}", new UseCaseRouteHandler())
{
Defaults = new RouteValueDictionary(new { action = "Index", id = "" }),
});

Identifying which view to show

Having commented out the call to the routing debugger, I then browsed to /Product/Edit/Load/17 and…BANG! An exception with the message,

The RouteData must contain an item named ‘controller’ with a non-empty string value

was shown. After some digging through the MVC source, it seems that the code responsible for identifying which view to create (the ViewEngine class does this) was also trying to find a controller token in the URL, in order to work out which subfolder of Views to look in. The Load method of EditProductController calls RenderView, passing “Edit” as the viewName argument. By altering this to “~/Views/Product/Edit.aspx” I was able to work around this issue.

This was a far from satisfactory solution however. Fully-qualifying all of the view names is a potential maintenance problem in the future, if views are moved or folders renamed. To combat this I introduced a UseCaseControllerBase class, from which EditProductController and FindProductController now inherit. This class overrides RenderView and works out the full path to the view. The following code shows how

public abstract class UseCaseControllerBase : Controller
{
    protected override void RenderView(string viewName, string masterName, object viewData)
    {
        string noun = this.RouteData.GetRequiredString("useCaseNoun");
        string fullViewName = string.Format("~/Views/{0}/{1}.aspx", noun, viewName);
        base.RenderView(fullViewName, masterName, viewData);
    }
}

The ideal resolution would be to customise the behaviour of the ViewEngine, however that is beyond the scope of this article.

This post demonstrates the flexibility of the routing subsystem provided by ASP .NET. It also shows how to improve the separation of functionality between controllers. If you are interested the sample code is available from CodePlex.

Technorati tags: