PranasLu's Blog

2010-05-07

ASP.NET MVC Naming conventions

Filed under: Programming — Tags: , — pranaslu @ 14:02

Naming Conventions

Excerpt from book [“Pro ASP.net MVC Framework” by Steven Sanderson]:

As you will have noticed by now, ASP.NET MVC prefers convention over configuration. This means, for example, that you don’t have to configure explicit associations between controllers and their views; you simply follow a certain naming convention and it just works. (To be fair, there’s still a lot of configuration you’ll end up doing in web.config, but that has more to do with IIS and the core ASP.NET platform.) Even though the naming conventions have been mentioned previously, let’s clarify by recapping:

  • Controller classesmust have names ending with Controller (e.g., ProductsController). This is hard-coded into DefaultControllerFactory: if you don’t follow the convention, it won’t recognize your class as being a controller, and won’t route any requests to it. Note that if you create your own IControllerFactory, you don’t have to follow this convention.
  • View templates (*.aspx, *.ascx), should go into the folder /Views/controllername. Don’t include the trailing string Controller here—views for ProductsController should go into /Views/Products (not /Views/ProductsController).
  • The default view for an action method should be named after the action method. For example, the default view for ProductsController’ s List action would go at /Views/ Products/List.aspx. Alternatively, you can specify a view name (e.g., by returning View("SomeView")), and then the framework will look for /Views/Product/SomeView.aspx.
  • When the framework can’t find a view called /Views/Products/Xyz.aspx, it will try /Views/Products/Xyz.ascx. If that fails, it tries /Views/Shared/Xyz.aspx and then /Views/Shared/Xyz.ascx. So, you can use /Views/Shared for any views that are shared across multiple controllers.

All of the conventions having to do with view folders and names can be overridden using a custom view engine.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: