Thursday, 13 November 2008

So that my code is strongly typed. I don’t use View() by itself because in unit testing I want to be sure my controller is returning the correct view. Well I’ve found a nice way to do it. If you don’t have a base controller you’ll need one, like so:

publicclass BaseController : Controller

{

protected ActionResult View(Type viewType, object viewData)

{

return (View(viewType.Name, viewData));

}

protected ActionResult View(Type viewType)

{

return (View(viewType.Name));

}

}

This will take the view name from the strongly typed reference to the class when you pass it by type and allow you to return your views like this:

public ActionResult Index()

{

return View(typeof(Views.en.Home.index));

}

public ActionResult About()

{

return View(typeof(Views.en.Home.about), AboutModel);

}

This is compile time checking and will save you from misspelling the view name (even if you unit test this can happen, particularly if you’re familiar with the dreaded copy and paste).