Jack M.
Jack M.

Reputation: 32080

Search for .cshtml in multiple locations in MVC 3?

When a user comes to my site, there may be a template=foo passed in the query string. This value is being verified and stored in the Session.

My file layout looks like this:

- Views/
  - Templates/
    - test1/
      - Home
        - Index.cshtml
    - test2/
      - Home
        - List.cshtml
  - Home/
    - Index.cshtml

Basically, if a user requests Index with template=test1, I want to use Views/Templates/test1/Index.cshtml. If they have template=test2, I want to use Views/Home/Index.cshtml (because /Views/Templates/test2/Home/Index.cshtml doesn't exist). And if they do not pass a template, then it should go directly to Views/Home.

I'm new to MVC and .NET in general, so I'm not sure where to start looking. I'm using MVC3 and Razor for the view engine.

Upvotes: 5

Views: 850

Answers (2)

Danny Tuppeny
Danny Tuppeny

Reputation: 42383

You can do this by creating a custom RazorViewEngine and setting the ViewLocationFormats property. There's a sample here that does it by overriding the WebFormViewEngine, but using the RazorViewEngine should work just as well:

public class CustomViewEngine : WebFormViewEngine
{
    public CustomViewEngine()
    {
        var viewLocations =  new[] {  
            "~/Views/{1}/{0}.aspx",  
            "~/Views/{1}/{0}.ascx",  
            "~/Views/Shared/{0}.aspx",  
            "~/Views/Shared/{0}.ascx",  
            "~/AnotherPath/Views/{0}.ascx"
            // etc
        };

        this.PartialViewLocationFormats = viewLocations;
        this.ViewLocationFormats = viewLocations;
    }
}

Upvotes: 1

Chris
Chris

Reputation: 4471

You could modify Scott Hanselman's Mobile Device demo to fit your needs. Instead of checking the user agent or if it's a mobile device, you could put your logic in to check the query string or your Session vars.

Upvotes: 1

Related Questions