Wednesday, 28 May 2008

Strongly-Typed View References with ASP.NET MVC Preview 3

Two short methods that'll give you compile-time type checking for your ASP.NET MVC views:

///<summary>Render the view whose implementation is defined by the supplied type.</summary>
protected ActionResult View(Type viewType, object viewData) {
    return(View(viewType.Name, viewData));
}

/// <summary>Render the view whose implementation is defined by the supplied type.</summary>
protected ActionResult View(Type viewType) {
    return(View(viewType.Name));
}

I've added these methods to a BaseController : Controller class, and my MVC controllers then inherit from my custom base class, but you could always add them via the extension-method syntax to the ordinary Controller supplied with ASP.NET MVC.

This means you can call your View() methods via a type reference that's checked by the compiler when you build, so instead of:

public ActionResult Info(int id) {
    Movie movie = dataContext.Movies.Single<Movie>(m => m.Id == id);
    return (View("Info", movie));
}

you can say

public ActionResult Info(int id) {
    Movie movie = dataContext.Movies.Single<Movie>(m => m.Id == id);
    return (View(typeof(Views.Movie.Info), movie));
}

and the reference to typeof(Views.Movie.Info) will be type-checked when you compile, so renaming or moving your view classes will cause a broken build until you fix the controllers that refer to them.

1 comment:

richardc said...

I like the post but cant seem to get it to work as Views dont get listed
im trying to type
return View(typeof(Views.PriceList), repListing);

but Views.PriceList can not be found and I get the error
Error 1 The type or namespace name 'Views' could not be found (are you missing a using directive or an assembly reference?)
any sugestions?