I would like to display the view in the folder if no controller/action matches.
For example www.site.com/Home/Index, if I have the normal default route {controller}/{action}/{id} then I need a HomeController with method Index.
And there is a folder in Views folder called Home and the file Index.cshtml
If i try www.site.com/About/Index i need to create the AboutController and the method index.
But I have just the folder About and file Index.cshtml.
I would like that if the default route does not match but I have a Folder and a File in the Views folder that match the patern: {controller} is the folder {action} is the view; then that view is displayed.
How could I achive that?
For missing actions you can override HandleUnknownAction.
For missing controllers you can implement a custom DefaultControllerFactory and override GetControllerInstance with something like this:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {
if (controllerType == null)
return new DumbController();
return base.GetControllerInstance(requestContext, controllerType);
}
class DumbController : Controller {
protected override void HandleUnknownAction(string actionName) {
try {
View(actionName).ExecuteResult(this.ControllerContext);
} catch (Exception ex) {
throw new HttpException(404, "Not Found", ex);
}
}
}
I came across the same issue recently while developing AJAX web applications where most of the pages don't actually need a controller (all the data is returned via Web API calls).
It seemed inefficient to have dozens of controllers all with a single action returning the view so I developed the ControllerLess plugin which includes a default view controller behind the scenes with a single action.
If you create a controller for your view, then MVC will use that. However, if you create a view without a controller, the request is re-routed via the default plugin controller.
It works with C# and VB.NET and us available at https://www.nuget.org/packages/ControllerLess
The source code is also available on GitHub at https://github.com/brentj73/ControllerLess
You cannot and shouldn't the way you want. Views cannot be addressed by design (in the web.config in the /views folder theres an HttpNotFoundHandler mapped to * to ensure this)
With that said, what you want here is not really standard so why do you want to do this, maybe we can come up with a better suggestion based on the reason behind this?
Never tried this, but here's a thought. You can setup constraints for the routes, and thus you should be able to create a route matching "{folder}/{file}" where you constraint them to valid values (you can google this, or seach her on SO), and set it to run on a FileController (arbitrary name) with some default action. Then, in that action, simply return the desired view. Something like:
public class FileController : Controller {
public ActionResult Default(string folder, string file) {
return View(folder + "/" + file);
}
}