Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 889
Jack M. Avatar asked Nov 05 '22 19:11

Jack M.


2 Answers

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;
    }
}
like image 163
Danny Tuppeny Avatar answered Nov 09 '22 16:11

Danny Tuppeny


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.

like image 21
Chris Avatar answered Nov 09 '22 15:11

Chris