开发者

What's the best practice approach to handling a mobile version of your asp.net mvc 2 app

The beauty of MVC is the separation of concerns, especially coming from the Asp.net webforms world.

I now have an MVC site with the Controllers, the actions, the model, and the views.

Looking at my site I can see that to serve a mobile version of it, all I have to do is swap out the Views section of it, and keep the Controllers, Actions, and Models untouched.

However, what is the best approach for this "swapping" out, specifically in Asp.net MVC 2?

Invetably there is some coupling between the controllers and the views. For example, certain actions reflect the names of the view, thus wiring by conventions. Sometimes the vi开发者_如何学编程ew is explicitly defined when returning the model.

Sometimes even, the actions in the controller contain conditions based on, is this an jax call, to return different views, like partial views for example.

so, with this in mind, say I'm happy with my current site, but now I want to create, say, an iPad version of it. So it my contain special js libraries for touch events, and the views may be less verbose, and of course the CSS different.

how do I build this into my MVC 2 project?

Cheers


One approach, off the top of my head, would be to create your own ViewEngine and override FindView, it has access to the controller context and therefore the HttpContext. You can use that to choose different views based on the user agent, using some kind of pattern, like appending _ipad or something.

Quick Example:

Global.asax

protected void Application_Start()
{
     RegisterRoutes(RouteTable.Routes);
     ViewEngines.Engines.Clear();
     ViewEngines.Engines.Add(new CustomViewEngine());
     AreaRegistration.RegisterAllAreas();
}

CustomViewEngine:

public class CustomViewEngine : WebFormViewEngine
{
    protected override IView CreateView(ControllerContext controllerContext, string viewPath,string masterPath)
    {
         if (controllerContext.HttpContext.Request.UserAgent.Contains("ipad"))
        {
             return base.CreateView(controllerContext, viewPath.Replace(".aspx","_ipad.aspx").Replace(".ascx","_ipad.ascx"), masterPath);
         }
         else
         {
             return base.CreateView(controllerContext, viewPath, masterPath);
        }
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜