TruMan1
TruMan1

Reputation: 36158

How do I redirect a mobile device with all query strings and hash in MVC4?

I noticed in MVC4, there is a built in method called Request.Browser.IsMobileDevice. How do I use this to check if the request is a mobile then redirect to the controller and action of /mobile/index? I want to carry over any query strings and the location hash that was in the URL. Is there a built in way to do this?

Upvotes: 2

Views: 1065

Answers (1)

Kevin Aenmey
Kevin Aenmey

Reputation: 13429

Generally you wouldn't want to redirect to a different controller and action for a mobile device since a mobile device should just require a different representation of the same model (you wouldn't want to duplicate your controller logic). If you create a view with the .Mobile.cshtml extension (for C# Razor views), MVC4 will, by convention, use this view for mobile devices.

E.g. if you have this view in your Home folder

Index.cshtml

by adding this view to your Home folder

Index.Mobile.cshtml

MVC4 will render Index.Mobile.cshtml on mobile devices and Index.cshtml on non mobile devices.

That said, there may be times when it is necessary to do something specific for mobile devices. E.g. if you wanted a different _Layout.cshtml for mobile devices, you could place the following in your _ViewStart.cshtml file

@{
    if(Request.Browser.IsMobileDevice)
    {
        Layout = "~/Views/Shared/_Layout.Mobile.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
}

Upvotes: 5

Related Questions