Sunday, September 28, 2014

Nested routing and folder in ASP.NET MVC

Nested routing and folder is doable in Laravel

Ever wanted to have a nested url and folder in ASP.NET MVC too? e.g., http://example.com/Hey/Jude/Dont/Make/It/Bad/1

It's doable in ASP.NET MVC by straying outside of convention-over-configuration. First, configure the routing, and then be explicit in your controller when specifying your view's path. Voila! you can now place your view anywhere you wanted it to, but most likely you'll want the folder hierarchy be symmetrical with your url

To cut to the chase, here it is in picture:



Note that we can't use @model directive on our view anymore with the approach above. So we have to explicitly use @inherits. @model ModelHere is shorthand for @inherits System.Web.Mvc.WebViewPage<ModelHere>, achieves the same thing. For details, see this: http://stackoverflow.com/questions/8127462/the-view-must-derive-from-webviewpage-or-webviewpagetmodel


Visual Studio cannot navigate anymore to your view with the approach above, however with ReSharper it's still able to navigate the view from your controller



Alternatively, if you don't like the sock drawer approach, you can use modular approach, here's one: http://www.ienablemuch.com/2014/09/modular-code-organization-in-aspnet-mvc.html

No comments:

Post a Comment