0

I am currently using DisplayModeProvider to check if a mobile request is coming in and serving up a Page.mobile.cshtml file if I detect a mobile request otherwise I'm serving the default page Page.cshtml. This also works as a fall-back - if there is a mobile request for PageX but PageX.mobile.cshtml does not exist but there is a PageX.cshtml, I serve PageX.cshtml. This is working as intended.

I would like to add to the fall-back behavior as I include support for tablet requests. So when a tablet device request is detected, if I have a Page.tablet.cshtml, it will go ahead and serve that file. If there isn't a ...tablet.cshtml file, I'd like it to try to serve the Page.mobile.cshtml file and if a Page.mobile.cshtml does not exist, we would serve the Page.cshtml file.

Is there a way to do this without having to create a ...tablet.csthml file for every page and Html.Partial'ing a ...mobile.cshtml within it?

mche
  • 616
  • 10
  • 16

1 Answers1

0

You can do that by changing the route preference dynamically. Define the hierarchy as you want like tablet first then mobile and then web pages.

Here is a sample how CustomViewEngine can do that:

public class MyViewEngine : RazorViewEngine
{
    public MyViewEngine()
        : base()
    {
        ViewLocationFormats = new[] {
        "~/Views/tab/{1}/%1/{0}.cshtml",
        "~/Views/mobile/{1}/%1/{0}.cshtml",
        "~/Views/{1}/%1/{0}.cshtml",
        "~/Views/Shared/{0}.cshtml"
    };

    PartialViewLocationFormats = new[] {
        "~/Views/tab/%1/{1}/{0}.cshtml",
        "~/Views/mobile/%1/{1}/{0}.cshtml",
        "~/Views/%1/{1}/{0}.cshtml",
        "~/Views/Shared/{0}.cshtml"
    };
   }
}

Here the view will be searched in the /Views/tab/ folder first then /Views/mobile/ followed by /Views/ and the /Views/Shared/ folders.

Detail of the implementation have been discussed here: ASP.NET MVC Custom View Routing

Rahatur
  • 3,147
  • 3
  • 33
  • 49