Thursday, 13 November 2008

Strongly typed View Names

I like the MVC framework but I want to type

public ActionResult Index()
{
    return View(Views.Home.Index);
}

Instead of

public ActionResult Index()
{
     return View("Index");
}

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:

public class 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).

1 comment:

MichaelGG said...

http://stackoverflow.com/questions/474065/strongly-typing-asp-net-controller-view-method-for-model-type#474418

With a bit more work, you can have the model strongly typed too.