One of the great things about MVC is the ability to direct any Controller Action to any named View that you want.
This means that I'm able to detect wether the browser is a mobile device and direct them to the Mobile View:
public ActionResult Index()
{
if (Convert.ToBoolean(filterContext.HttpContext.Request.Browser["IsMobileDevice"]))
{
return View("Index_mobile")
}
return View();
}
This works great. My Index_mobile.aspx view has a Master Page (just like any other view) that sets up the doc type and styles, and I can render the view as normal. The doc type I used is:
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
Another way is to use an ActionFilterAttribute to detect if the browser is a mobile device and then append "_mobile" to the current view.
The benefit of using an action filter is that I can just mark up my Action Method or Controller with this attribute and it will automatically render a mobile view.
[MobileUserFilter]
public ActionResult Index()
{
return View();
}
public class MobileUserFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (Convert.ToBoolean(filterContext.HttpContext.Request.Browser["IsMobileDevice"]))
{
var action = (string)filterContext.RouteData.Values["action"];
var viewName = ((ViewResult) filterContext.Result).ViewName;
if (string.IsNullOrEmpty(viewName)) viewName = action;
var result = new ViewResult
{
ViewName = (viewName + "_mobile"),
MasterName = ((ViewResult) filterContext.Result).MasterName,
ViewData = ((ViewResult) filterContext.Result).ViewData,
TempData = ((ViewResult) filterContext.Result).TempData
};
filterContext.Result = result;
filterContext.HttpContext.Response.Clear();
}
base.OnActionExecuted(filterContext);
}
}
There we have it now we have a mobile site:
By the way, I'm testing my mobile site on Openwave Phone Simulator which you can download here. Does anybody use a better Phone Emulator? Let me know if you do, I'd love to try it out.