Angular.NET – Helpers for ASP .NET MVC 4

ASP .NET MVC is a great web-server framework and, in my opinion, a HUGE improvement over regular ASP .NET WebForms. Among many features, it has routing, helper methods to generate views, declarative model validation (data annotations), automatic model binding for different media types (with model validation), support for dependency injection, etc.

On the other hand, AngularJS is a great client-side framework that helps you to create professional applications using JavaScript. It’s loaded with features such as client-side routing, directives for custom behavior like model binding (ngModel) and model validation, filters, message dispatcher, dependency injection, etc.

Currently, creating HTML forms with model bindings and the respective validations and error messages for each field in the form can be a tedious, error-prone task. Suppose we have the following model class:

using System;
using System.ComponentModel.DataAnnotations;

public class Person
{
    public int Id { get; set; }

    [Required]
    [StringLength(25)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(25)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

Let’s look at an example of how you would create a simple but fully functional form (with validations) in AngularJS for this model (for more information, see the form and ngModel directives):

<form autocomplete="off" class="form-horizontal ng-cloak" id="personalForm" method="POST" name="personalForm" ng-submit="save(personalForm)" novalidate>
    <div class="control-group" ng-class="{ error: personalForm.FirstName.$invalid && personalForm.FirstName.$dirty }">
        <label class="control-label" for="FirstName">First Name</label>
        <div class="controls">
            <input autofocus id="FirstName" name="FirstName" ng-maxlength="25" ng-model="FirstName" required type="text" />
            <span class="help-inline" ng-show="personalForm.FirstName.$error.required && personalForm.FirstName.$dirty">The First Name field is required.</span>
            <span class="help-inline" ng-show="personalForm.FirstName.$error.maxlength && personalForm.FirstName.$dirty">The field First Name must be a string with a maximum length of 25.</span>
        </div>
    </div>
    <div class="control-group" ng-class="{ error: personalForm.LastName.$invalid && personalForm.LastName.$dirty }">
        <label class="control-label" for="LastName">Last Name(s)</label>
        <div class="controls">
            <input id="LastName" name="LastName" ng-maxlength="25" ng-model="LastName" required type="text" />
            <span class="help-inline" ng-show="personalForm.LastName.$error.required && personalForm.LastName.$dirty">The Last Name(s) field is required.</span>
            <span class="help-inline" ng-show="personalForm.LastName.$error.maxlength && personalForm.LastName.$dirty">The field Last Name(s) must be a string with a maximum length of 25.</span>
        </div>
    </div>
    <div class="control-group">
        <div class="controls">
            <button class="btn btn-primary" type="submit">Save</button>
            <button class="btn" type="button" ng-click="cancel()">Cancel</button>
        </div>
    </div>
</form>

Now, that was only a form with two fields (I know, I have a several rules and validation messages, but it’s a real-world case). This works like a charm but, as you can see, it requires a great deal of maintenance effort. You need to add all the validation directives, the appropriate help messages and the rules for when to display/hide them. You will need to be careful to keep you form validations in sync with your server side models if any of the following occur:

  • The names of your model properties are modified.
  • The validations for a specific property are added/removed.
  • The values for such validations are changed (for example, the max value for a number or the max length for a string field)

That’s a lot work for me. Since I’m too lazy for all that, I thought there must be something that could save me some time when coding and maintaining my code. It turns out there is a great ASP .NET MVC feature that could come to the rescue: HTML helper extension methods. So, inspired by a solution that I used for Knockout some time ago (Knockout MVC) and by ASP .NET MVC’s jQuery unobtrusive validation, I created a small library for AngularJS that integrated both features (binding and validation generation).

Using this library, the same view can be created in Razor as follows:

@using AxSoft.Angular.Net

@model AxSoft.Model.Person
@using (var form = Html.BeginAngularForm("personForm", "save", "person", new { @class = "form-horizontal ng-cloak" }))
{
    <div class="control-group" @form.NgClassError(m => m.FirstName)>
        @form.Label(m => m.FirstName)
        <div class="controls">
            @form.TextBox(m => m.FirstName, new { autofocus = "" })
            @form.ValidationsFor(m => m.FirstName, true)
        </div>
    </div>
    <div class="control-group" @form.NgClassError(m => m.LastName)>
        @form.Label(m => m.LastName)
        <div class="controls">
            @form.TextBox(m => m.LastName)
            @form.ValidationsFor(m => m.LastName, true)
        </div>
    </div>
    
    <div class="control-group">
        <div class="controls">
            <button class="btn btn-primary" type="submit">Save</button>
            <button class="btn" type="button" ng-click="cancel()">Cancel</button>
        </div>
    </div>
}

A few things to note:

  • You need to import the AxSoft.Angular.Net (or add it to the namespaces node of you web.config file under the Views folder).
  • You have to declare the model type for the extension methods to work properly. Note that this declaration only acts as an indication of the type of model you want to get the properties from, but you don’t need to pass an actual model instance to the view.
  • You can create a form almost exactly as you would using the Html.BeginForm method, supplying the following values:
    • A form name: this will be used for the validation message conditions; also, AngularJS will create a property on your controller’s scope with the same name as the form.
    • The name of the method to be invoked when the form is submitted (optional); this is used to output the ng-submit directive in the form ng-submit="nameOfMethod(nameOfForm)". The form instance is passed to the method so that you can check the validity of the form through form.$valid. The default value is "save"
    • The name of the scope property that will hold the model object (optional).
    • An object or dictionary instance containing custom HTML attributes to be set on the form (optional).

The invocation of Html.BeginAngularForm will return a generic AngularForm object which you can use to create your form controls and bindings.

You can create controls for specific model properties using the methods TextBox, Hidden, TextArea, Password, RadioButton, CheckBox, and Dropdown. These methods will output the corresponding ngModel directive as well as all the registered validations found in the ValidationAttribute‘s of the property.

The method ValidationsFor will generate span elements for each registered validation for the property. Each element will have a CSS class with the value you specify in the AngularConfiguration.HelpCssClass property (the default is "help-inline").

The method Label is similar to Html.LabelFor, with the only advantage of creating a for attribute that will match the id attribute of the control generated for the same property.

Lastly, the method NgClassError will output an ng-class directive that will activate the error CSS class of the element when any of the validations for that property fail to pass. The name of this class will be given by the value of the AngularConfiguration.ErrorCssClass property (the defautl is "error").

Interested? Grab the code from Github and play with it. Any feedback is welcome.

In a future tutorial: how to extend the validation mechanism with custom validation attributes and directives. Stay tuned.

Advertisements

Dependency injection in ASP .NET MVC with Autofac

Dependency injection (DI) is one form of inversion of control, which is a technique used to reduce coupling between components by replacing hard-coded dependencies with abstractions (usually interfaces) that are passed (injected) to the consuming component.

DI offers a number of benefits and encourages good practices that result in other benefits, such as:

  • Modularity: dependency injection practices favor a more modular application design.
  • Simplified Unit testing
  • Dynamic behavior: allows the changing of concrete implementations of services at runtime or compile time.
  • Scalability
  • Decoupling
  • Service life-cycle management: service containers can take care of the creation, sharing, and disposal of object instances when needed (i.e., we don’t need to call IDisposable.Dispose ourselves).

There are many CI containers out there, but today I will talk about one that I like in particular because it’s simple, flexible and light: Autofac. More specifically, I will show you how you can use it in your ASP .NET MVC projects.

We’ll start by creating an MVC project in Visual Studio (in this case, MVC 4). Choose the template that best suits your needs; in this example I chose the Basic template and I called it AutofacExample. Open the Package Manager Console and execute the following command to install Autofac for MVC 4:

Install-Package Autofac.Mvc4

(You can use the Manage NuGet Packages option, and then search for Autofac MVC4, if you’re more comfortable with the UI version.)

Suppose we already have a few business entities, including Customer. Let’s start by defining some simple services (interfaces and implementation).

using System.Collections.Generic;
using AutofacExample.Models;
 
namespace AutofacExample.Services
{
	public interface IRepository<T> where T : class
	{
		IEnumerable<T> All();
 
		T Get(int id);
 
		void Update(T entity);
 
		void Delete(int id);
	}
 
	public interface ICustomerRepository : IRepository<Customer>
	{
		IEnumerable<Receipt> GetReceipts(int customerId);
	}
 
	public class CustomerRepository : ICustomerRepository
	{
		public IEnumerable<Customer> All()
		{
			// Code goes here
		}
 
		public Customer Get(int id)
		{
			// Code goes here
		}
 
		public void Update(Customer entity)
		{
			// Some code
		}
 
		public void Delete(int id)
		{
			// Code goes here
		}
 
		public IEnumerable<Receipt> GetReceipts(int customerId)
		{
			// Code goes here
		}
	}
}

Next, in our MvcApplication class (in the Global.asax.cs file), we create a RegisterServices method, which we’ll invoke in Application_Start:

private static void RegisterServices()
{
	var builder = new ContainerBuilder();
	var assembly = Assembly.GetExecutingAssembly();

	// Tell autofac to scan the assembly and register all subclasses of System.Web.Mvc.Controller 
	builder.RegisterControllers(assembly);

	// Register repository, and expose it only through the ICustomerRepository interface
	builder.RegisterType<CustomerRepository>()
		.As<ICustomerRepository>().InstancePerHttpRequest();
 
	// Build the container and set it as the default dependency resolver
	var container = builder.Build();
	var resolver = new AutofacDependencyResolver(container);
	DependencyResolver.SetResolver(resolver);
}

(You will need to add using statements for Autofac and Autofac.Integration.Mvc.)

Notice we declared our repository’s lifetime as per HTTP request. This means that the container will dereference the instance after the request has completed so that it can be garbage-collected. If the service implements the IDisposable interface, the Dispose method will be invoked before the instance is released.

Finally, we can add a CustomerController (or use the default HomeController) to consume our newly created CustomerRepository, through its interface. The controller will declare a constructor dependency to ICustomerRepository and Autofac will take care of resolving and instantiating the dependencies and the controller itself.

using AutofacExample.Services;
using System.Web.Mvc;
 
namespace AutofacExample.Controllers
{
	public class CustomerController : Controller
	{
		private readonly ICustomerRepository _customerRepository;
 
		public CustomerController(ICustomerRepository customerRepository)
		{
			_customerRepository = customerRepository;
		}
 
		public ActionResult Index(int id)
		{
			var customer = _customerRepository.Get(id);
			return View(customer);
		}
	}
}

This is a ridiculously simple example, but in a real life application, dependencies would be nested in many levels. For example, our CustomerRepository could have a dependency to a DataService, which in turn may declare dependencies to other services. Autofac will kindly take care of all that mess and deliver what we ask for (as long as all objects involved are properly registered and configured).

Usually, an application may use many services and registering them one by one would be tedious and error prone. But if we use some naming standards for our services we can use assembly scanning and register many at once. For example:

var assembly = Assembly.GetExecutingAssembly();
// Assuming all repository names end with Repository
builder.RegisterAssemblyTypes(assembly)
	.Where(t => t.Name.EndsWith("Repository"))
	.AsImplementedInterfaces();

If you need more control over how a specific service is instantiated, you can specify it:

// Use the connection string named DefaultConnection
builder.Register(d => new Database("DefaultConnection"))
	.As<IDatabase>().InstancePerHttpRequest();

There are many more tips and tricks when using Autofac as your dependency injection container in ASP .NET MVC. Stay tuned.

Parameter validation in ASP .NET MVC 4

Routing in ASP .NET MVC is a great feature. Among other things, it lets you create stateless applications more easily and in a more elegant way and break away from practices that rely on cookies/session variables. If you have a controller action like the following:

public class SiteController : Controller
{
	public ActionResult News(int id)
	{
		// Do some interesting stuff with that id parameter
	}
}

And if you leave the default route that comes with most MVC project templates, you will have that action automatically respond to a route (read URL) like /Site/News/1. How cool is that?

However, there’s a small catch in the route-matching mechanism. If the route is requested with an invalid id parameter (as in /Site/News/blah) or a missing one (/Site/News) you will get an awful error:

System.ArgumentException: The parameters dictionary contains a null entry for parameter ‘id’ of non-nullable type ‘System.Int32’ for method ‘System.Web.Mvc.ActionResult News(Int32)’ in ‘Tbt.Controllers.SiteController’. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Yep, that’s a 500 (Internal Server Error) page. That’s basically because the routing engine could find the controller and the action but had trouble parsing the parameter (that happens to be a value type). That might not sound like a big deal (and probably isn’t in most projects); after all, who will be using our web app’s URLs in ways they’re not intended to be used? Well, in my experience, search engines’ crawlers seem to do that. And if good SEO is a concern, you might not want to make the search engines “think” your app crashes for no apparent reason.

Of course, there’s an easy, straightforward way to fix that. You guessed right: make the parameters nullable.

public class SiteController : Controller
{
	public ActionResult News(int? id)
	{
		if (!id.HasValue)
		{
			// Redirect or return the appropriate HTTP code here
		}
		int realId = id.Value;
		// Do some interesting stuff with the realId variable
	}
}

However, depending on the amount of actions the application may have, this can become a cumbersome, tedious task and can distract us from our main goal: write awesome code. That’s what made me look for a better solution, and this is what I came up with.

Using the ActionMethodSelectorAttribute class

According to the MSDN documentation, the ActionMethodSelectorAttributeRepresents an attribute that is used to influence the selection of an action method“. And that’s exactly what we will do: intercept the request and make sure it fulfills all the requirements (in this case, having valid values for all non-nullable parameters); if not, the app will automatically issue a 404 (Not found) HTTP status code and our action method will not be called. Here’s the code:

Update (2015-05-27): Added default value check as suggested by Steven Sproat.

using System;
using System.Reflection;
using System.Web.Mvc;

public class NonNullableParametersAttribute : ActionMethodSelectorAttribute
{
	public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
	{
		var methodParams = methodInfo.GetParameters();

		foreach (var parameterInfo in methodParams)
		{
			if (parameterInfo.HasDefaultValue)
			{
				continue;
			}

			var paramType = parameterInfo.ParameterType;
			if (!IsSimpleType(paramType))
			{
				continue;
			}

			var value = controllerContext.Controller.ValueProvider.GetValue(parameterInfo.Name);
			if (value == null || value.AttemptedValue == null || !CanParse(value.AttemptedValue, paramType, value.Culture))
			{
				return false;
			}
		}

		return true;
	}

	private static bool IsSimpleType(Type t)
	{
		return t.IsPrimitive || t.IsEnum || t == typeof(Decimal) || t == typeof(DateTime) || t == typeof(Guid);
	}

	private static bool CanParse(object rawValue, Type destinationType, IFormatProvider formatProvider)
	{
		try
		{
			var test = Convert.ChangeType(rawValue, destinationType, formatProvider);
			return test != null;
		}
		catch
		{
			return false;
		}
	}
}

Then, we decorate our action methods like so:

[NonNullableParameters]
public ActionResult News(int id)
{
	// Do your stuff using that id parameter
}

The NonNullableParametersAttribute will handle any number of parameters of primitive type (int, double, etc) and some non-primitive value types (decimal, DateTime, Guid) for you.