views:

47

answers:

2

In ASP.NET MVC 2 project, how might I go about writing a custom view engine that allows custom tokens to be used when searching for views?

Specifically, I'm trying to achieve this:

In PagesController:

public ActionResult ViewPage(string folder, string page)
{
  return View(folder, page);
}

I want the view engine to search for the view in the directory: /Views/Pages/[folder]/

How might I achieve this without knowing the folder names ahead of time? Ideally, this customized view engine would only be used for this single controller.

A: 

You don't need to implement your own viewengine to solve this issue. You can simply supply the path to the view you want. Something like this:

return View("~/Views/Pages/FolderName/ViewName.aspx");

You example could look something like this:

public ActionResult ViewPage(string folder, string page) {
    return View(string.Format("~/Views/Pages/{0}/{1}.aspx", folder, page));
}
Mattias Jakobsson
Yes, I realize that I can do this and in fact, that's what I'm doing right now. I'd like to be able to use a view engine if possible though.
Brian Vallelunga
@Brian Vallelunga, Why would you want to do that? Being able to pass the location of the view like this is a feature of the viewengine. Why duplicate that? It will most likely lead to code that is less maintainable.
Mattias Jakobsson
I guess you're right in this instance. What you don't get is the automatic 404 checking, for example. That's easy enough to add of course though.
Brian Vallelunga
@Brian Vallelunga, You will get the same functionality as if you would write this in the viewengine. What you do here is simply overwriting the default view location. So the same thing will happen after that. You don't get a 404 exception when a view isn't found. You will get a exception from the framework.
Mattias Jakobsson
A: 

If these values change by request (...it looks like that) then you need to overwrite CreateView. I have not done it myself but in one question on SO somebody said its possible:

http://stackoverflow.com/questions/3063619/localization-with-separate-language-folders-within-views/3065647#3065647

Malcolm Frexner