ASP.NET
ModelBinding ASP.NET MVC and Multiple Field Validation
Aug 17th
This tip comes to you from my blog, but the hat-tip goes to Andres Nelson whom I work with at my current client who actually showed me how to do this.
The Scenario
You have a grid with multiple fields. These fields are dependent upon each other. If one field is empty, then the other field is empty. At that point you want to display ONE error message informing the user that something is wrong, but you want to highlight both fields, as shown below in Figure 1-1. Please excuse the blurring of everything, but its NDA, you know how it goes.
Click for a larger view.
Figure 1-1: Highlighting both fields, but providing one error message.
Solution
I never thought of this, but its actually pretty simple, so again – hat tip to Andres. Simply add two ModelState errors, one for each property you want highlighted. However, for the second field, provide and empty string. MVC will not show that error in the validation summary, but the field will still get highlighted. Here’s the code -
bindingContext.ModelState.AddModelError("Field1Name", "Hey! Bad Stuffs Happens!");
// The one below will not show up in the validation summary, but the field will be highlighted.
bindingContext.ModelState.AddModelError("Field2Name", String.Empty);
That’s it!

ASPNET MVC: Handling Multiple Buttons on a Form with jQuery
Jun 4th
Sometimes your task in MVC involves many buttons in the same form. Such as the screen shot here. 
What happens in most situations is that you end up having some code that kind of looks like this:
<form action="/foo/save"> <!-- My HTML and multiple buttons --> </form>
… and then the code looks like this
public ActionResult Save(CustomerList customers, string buttonName)
{
if(buttonName == "Save")
{
// do something
}
else if (buttonName == "Reload")
{
// etc, etc
}
// Other if's, etc, etc
}
We can solve this with a little jQuery. By attaching a click handler to the button we can tell the form where we want it to go. Therefore keeping our controllers actions very slim.
Here’s the jQuery:
// This assumes your buttons have id's "save-button" and "update-button"
$("#save-button").click(function () {
// Redirect to add facility for Credit Exposure
var form = $(this).parents('form:first');
form.attr('action', '<%=Url.RouteUrl(new { controller = "foo", action = "save" }) %>');
});
$("#reload-button").click(function () {
// Redirect to add facility for Credit Exposure
var form = $(this).parents('form:first');
form.attr('action', '<%=Url.RouteUrl(new { controller = "foo", action = "reload" }) %>');
});
Now when the user clicks “Save” they will go to the “Save” Action on the “FooController”. When the user clicks “Reload” they will go to the “Reload” action on the”FooController”. No more logic switches in the Controller.
You can download and example here (minus the MVC Goo):
MVC: Unit Testing Action Filters
Apr 21st
Certain parts of ASP.NET MVC can be a real pain to test. Namely Model Binders, Action Filters and anything that relies on some magic “Context” that seems to derive from HttpContext, ControllerContext, RequestContext, etc.
Below, I’ve outlined how I’ve unit tested a Action Filter. You could extrapolate some of this code into a base Test Class, but I’ve left it all in one place so you can see whats going on.
Background
The action filter filters out Employees based upon a “group”. Employee id’s are in a table and if the employee id has a parent id it is part of a group. I want to be able to put this action filter on any action or controller where groups should not be allowed. If the employee is part of a group, I want to change the ViewResult to ContentResult and stuff some html in there for the user to see. Therefore if the user cannot cannot access this screen, they’ll still see the master page, etc, but the view will be some plain text letting them know that they cannot view the page through a group.
Here’s the code:
using System.Web.Mvc;
using SharpArch.Core;
namespace Agilevent.UI.Web.ActionFilters
{
public class EmployeeGroupRestrictedActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Get Employee Id
var employeeId = int.Parse(filterContext.RouteData.GetRequiredString("employeeId"));
var employeeInfo = SafeServiceLocator<IEmployeeInfoService>.GetService().GetById(employeeId);
if (employeeInfo.IsGroup)
{
filterContext.Result = new ContentResult {Content = HtmlResultString};
}
base.OnActionExecuted(filterContext);
}
public string HtmlResultString
{
get { return "This screen is only accessible by selecting a the actual employee. You cannot view it through a group id."; }
}
}
}
The Unit Test
The unit test mocks out the Action Executed Context with the values that I need mocked out. I make sure that the RouteData contains a value that I need and then the Service Locator is set up to return a mock service which will return a mocked out Employee with a known state. Since the employee is a group the test will fall into the ContentResult and we can test from there.
Here’s the code:
using System;
using System.Security.Policy;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.ServiceLocation;
using Moq;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using StructureMap;
using StructureMap.ServiceLocatorAdapter;
namespace Agilevent.UnitTests.MVC.ActionFilters
{
[TestFixture]
public class EmployeeGroupRestrictedActionFilterTests
{
private Container _container;
private Mock<IEmployeeInfoService> _employeeInfoService;
private EmployeeInfo _employeeInfo;
[Test]
public void should_not_be_able_to_continue_if_the_employee_id_is_a_group()
{
// Set up fake employee info as a group
_employeeInfo = new EmployeeInfo();
_employeeInfo.IsGroup = true;
// Set up employee info service to return the fake employee when called with "123"
_employeeInfoService = new Mock<IEmployeeInfoService>();
_employeeInfoService.Setup(b => b.GetById(It.Is<int>(i => i == 123))).Returns(_employeeInfo);
// Set up the container & Service Locator
_container = new Container();
_container.Configure(x => x.For<IEmployeeInfoService>().Use(_employeeInfoService.Object));
ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(_container));
// Mock out the context to run the action filter.
var request = new Mock<HttpRequestBase>();
var httpContext = new Mock<HttpContextBase>();
httpContext.SetupGet(c => c.Request).Returns(request.Object);
var routeData = new RouteData(); //
routeData.Values.Add("employeeId", "123");
var actionExecutedContext = new Mock<ActionExecutedContext>();
actionExecutedContext.SetupGet(r => r.RouteData).Returns(routeData);
actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object);
var filter = new EmployeeGroupRestrictedActionFilterAttribute();
filter.OnActionExecuted(actionExecutedContext.Object);
// Assert
Assert.That(actionExecutedContext.Object.Result, Is.InstanceOfType(typeof(ContentResult)));
Assert.That((actionExecutedContext.Object.Result as ContentResult).Content, Is.EqualTo(filter.HtmlResultString));
}
}
}
I hope that helps someone out there, I know I’ll probably even come back at some point in the future to see how I did it.
Enjoy.
No IE6 ActionFilter for ASP.NET MVC
Mar 31st
*** Update ***: I’ve also created a cheap jQuery plugin for this as well. See the bottom of the post
There’s a lot of talk on Twitter today about IE6. I’m building a web application in my free time and I didn’t want to support IE6. Will I lose users? Yes, a few, but I don’t care. To try to help circumvent someone with IE6 hitting my site I wrote an ASP.NET MVC Action Filter to block anything less than IE7. It’s rather crude, but it works.
Please note, I’ve only tested this with IE Tester, so real IE6 users… well YMMV.
Here’s the code:
public class NoIe6Attribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var browser = filterContext.HttpContext.Request.Browser.Browser;
var major = filterContext.HttpContext.Request.Browser.MajorVersion;
if(browser.ToLowerInvariant() == "ie" && major <= 6)
{
filterContext.Result = new ContentResult {Content = Ie6NotSupportedHtml};
}
}
public string Ie6NotSupportedHtml
{
get
{
return @"<html>
<head>
<title>IE6 Not Supported</title>
<style>
body {
background-color: #111;
color: #FFF;
font-family: Trebuchet MS, 'Helvetica Neue', Arial, sans-serif;
font-weight: light;
letter-spacing: 1px;
line-height: 1.5;
}
h1 {
font-size: 60px;
font-weight: bold;
line-height: 1;
margin: 40px 10px 10px;
text-align: center;
}
h2 {
font-size: 20px;
font-weight: normal;
line-height: 1.2;
margin-bottom: 20px;
margin-right: 10px;
margin-left: 10px;
text-align: center;
}
a:link,
a:visited,
a:hover,
a:focus,
a:active {
border: none;
color: #5EA9FF;
font-weight: bold;
letter-spacing: 1.5px;
text-decoration: none;
}
.container {
margin: 0 auto;
width: 540px;
}
</style>
</head>
<body>
<divcontainer>
<h1>Sorry, we do not support IE6.</h1>
<h2>Please <a href=""http://www.microsoft.com/ie"" target=""_blank"" title=""Upgrade IE"">upgrade your browser</a> to a recent version of Internet Explorer</h2></div>
</body>
</html>";
}
}
}
Explaining It
It’s crude, but so it IE6, so we’re fighting fire with fire here. You don’t need to include any fancy HTML or whatever. If this filter finds that you’re running IE6, it will change the ViewResult to a ContentResult and stuff some hard-coded HTML into that result.
Result
This is what you’ll see if you visit an action/controller/etc that is decorated with this attribute. (click for bigger image)
How to Use It
Personally I like to block _all_ IE6 access (for my current project), so I throw it on my BaseController (the class all of my controllers inherit from). You can also slap it on an action, or you can slap it on a single controller if you’re doing some wonky stuff in an individual controller.
[NoIe6]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
// or on an action
public class HomeController : Controller
{
[NoIe6]
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
Enjoy.
Let me know if you see any errors with it. I whipped it up a few weeks ago and never touched it since.
Update
jQuery Plug-In
Some people said they would rather have this as a jQuery plug-in. I understand that, but I still prefer to go on the server side. That way I don’t get the entire HTML of the page sent back to the user. They get what I give them when they use IE6. However, not everyone thinks like me. So here is a jQuery plugin for it.
Download the Plug-in: jquery.noie6.js
Code:
/**
* jQuery noie6
* A jQuery plugin to display text for IE6 Users.
*
* v0.0.1 - 31 March 2010
*
* Copyright (c) 2010 Donn Felker (http://twitter.com/donnfelker)
* Dual licensed under the MIT and GPL licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/gpl-license.php
*
* Use $.noie6();
*
**/
;jQuery.noie6 = function (x) {
// Stolen from thickbox
if (typeof document.body.style.maxHeight === "undefined") {
$("body").html("<style> body {background-color: #111;color: #FFF;font-family: Trebuchet MS, 'Helvetica Neue', Arial, sans-serif; font-weight: light; letter-spacing: 1px; line-height: 1.5; } h1 { color:#FFF; font-size: 60px; font-weight: bold; line-height: 1; margin: 40px 10px 10px; text-align: center; } h2 { color: #FFF; font-size: 20px; font-weight: normal; line-height: 1.2; margin-bottom: 20px; margin-right: 10px; margin-left: 10px; text-align: center; } a:link, a:visited, a:hover, a:focus, a:active { border: none; color: #5EA9FF; font-weight: bold; letter-spacing: 1.5px; text-decoration: none; } .container { margin: 0 auto; width: 540px; } </style><div class=\"container\"> <h1>Sorry, we do not support IE6.</h1> <h2>Please <a href=\"http://www.microsoft.com/ie\" target=\"_blank\" title=\"Upgrade IE\">upgrade your browser</a> to a recent version of Internet Explorer</h2> </div>");
}
};
Usage:
<script>
$(function() { $.noie6(); }
</script>
This will give you the same screen I showed above (black background, white text, etc). However, this will not get run until document.ready _and_ you will have a whole goop of HTML that came down with the page. Note: The browser detection is from some Thickbox code.
ASP.NET MVC REST API WINDSOR CONTROLLER FACTORY
Mar 11th
I’m using the ASP.NET MVC REST Toolkit for a REST API I’m building for a mobile infrastructure. Long story short, it will be responsible for service hundreds of thousands (if not millions) of users through their mobile phones and rich applications (Android, iPhone and eventually the WP7 Phones).
The one thing that the Toolkit did not provide out of the box was a way to use a container in the controller factory. Therefore I altered the ResourceControllerFactory to use Windsor Container as its default container. The code works great and I’m able to utilize dependency injection all throughout my app now.
The code for this is below:
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
using Castle.MicroKernel;
namespace System.Web.Mvc.Resources
{
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Mime;
using System.Text;
using System.Web.Routing;
/// <summary>
/// Specialized ControllerFactory that augments the base controller factory to make it RESTful - specifically, adding
/// support for multiple formats, HTTP method based dispatch to controller methods and HTTP error handling
/// </summary>
public class ResourceControllerFactory : IControllerFactory
{
// Note: This has been changed from the regular controller factory provided
// by the ASP.NET Team so that we can use Windsor Container to resolve
// container dependencies.
readonly IKernel _kernel;
const string restActionToken = "$REST$";
public ResourceControllerFactory(IKernel kernel)
{
_kernel = kernel;
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
IController ic = _kernel.Resolve<IController>(controllerName.ToLowerInvariant() + "controller");
Controller c = ic as Controller;
if (c != null && WebApiEnabledAttribute.IsDefined(c))
{
IActionInvoker iai = c.ActionInvoker;
ControllerActionInvoker cai = iai as ControllerActionInvoker;
if (cai != null)
{
c.ActionInvoker = new ResourceControllerActionInvoker();
string actionName = requestContext.RouteData.Values["action"] as string;
if (string.IsNullOrEmpty(actionName))
{
// set it to a well known dummy value to avoid not having an action as that would prevent the fixup
// code in ResourceControllerActionInvoker, which is based on ActionDescriptor, from running
requestContext.RouteData.Values["action"] = restActionToken;
}
}
}
return ic;
}
public void ReleaseController(IController controller)
{
_kernel.ReleaseComponent(controller);
}
// This ActionInvoker allows us to dispatch to a controller when no action was provided by the routing
// infrastructure, but the information is available in the request's HTTP verb (GET/PUT/POST/DELETE)
class ResourceControllerActionInvoker : ControllerActionInvoker
{
public ResourceControllerActionInvoker()
{
}
protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
{
if (actionName == restActionToken)
{
// cleanup the restActionToken we set earlier
controllerContext.RequestContext.RouteData.Values["action"] = null;
List<ActionDescriptor> matches = new List<ActionDescriptor>();
foreach (ActionDescriptor ad in controllerDescriptor.GetCanonicalActions())
{
object[] acceptVerbs = ad.GetCustomAttributes(typeof(AcceptVerbsAttribute), false);
if (acceptVerbs.Length > 0)
{
foreach (object o in acceptVerbs)
{
AcceptVerbsAttribute ava = o as AcceptVerbsAttribute;
if (ava != null)
{
if (ava.Verbs.Contains(controllerContext.RequestContext.GetHttpMethod().ToUpperInvariant()))
{
matches.Add(ad);
}
}
}
}
}
switch (matches.Count)
{
case 0:
break;
case 1:
ActionDescriptor ad = matches[0];
actionName = ad.ActionName;
controllerContext.RequestContext.RouteData.Values["action"] = actionName;
return ad;
default:
StringBuilder matchesString = new StringBuilder(matches[0].ActionName);
for (int index = 1; index < matches.Count; index++)
{
matchesString.Append(", ");
matchesString.Append(matches[index].ActionName);
}
return new ResourceErrorActionDescriptor(controllerDescriptor, HttpStatusCode.Conflict, string.Format(CultureInfo.CurrentCulture, "Error dispatching on controller {0}, conflicting actions matched: (1)", controllerDescriptor.ControllerName, matchesString.ToString()));
}
}
return base.FindAction(controllerContext, controllerDescriptor, actionName) ??
new ResourceErrorActionDescriptor(controllerDescriptor, HttpStatusCode.NotFound, string.Format(CultureInfo.CurrentCulture, "Error dispatching on controller {0}, no actions matched", controllerDescriptor.ControllerName));
}
// This class is used when we don't find an ActionDescriptor or find multiple matches
// in this case we want to return an error response but throwing an HttpException from
// FindAction bypasses the InvokeExceptionFilters, so instead we throw in this custom ActionDescriptor
class ResourceErrorActionDescriptor : ActionDescriptor
{
ControllerDescriptor controllerDescriptor;
string message;
HttpStatusCode statusCode;
public ResourceErrorActionDescriptor(ControllerDescriptor controllerDescriptor, HttpStatusCode statusCode, string message)
{
this.message = message;
this.statusCode = statusCode;
this.controllerDescriptor = controllerDescriptor;
}
public override string ActionName
{
get { return restActionToken; }
}
public override ControllerDescriptor ControllerDescriptor
{
get { return this.controllerDescriptor; }
}
public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)
{
HttpException he = new HttpException((int)this.statusCode, this.message);
ResourceErrorActionResult rear;
if (!WebApiEnabledAttribute.TryGetErrorResult2(controllerContext.RequestContext, he, out rear))
{
rear = new ResourceErrorActionResult(new HttpException((int)this.statusCode, this.message), new ContentType("text/plain"));
}
return rear;
}
public override ParameterDescriptor[] GetParameters()
{
return new ParameterDescriptor[0];
}
}
}
}
}
You can easily replace the Windsor stuff with StructureMap, NInject, Autofac, etc.
Enjoy.


