利用MVC4新特性为站点添加移动视图

MVC4发布之后就第一时间观看了Scott介绍视频,其中提到很多新特性,我边看边记了下来,附在本文末尾,以备参考。

然后,就迫不及待地把windvoice升级到了mvc4,为windvoice添加了js和css合并和压缩,尝试了web api。值得注意的是,js和css的bundling功能必须在web.config中compilation 的debug设置为false的情况下才会起作用。

本还想为windvoice添加web view,但一直拖拖拉拉直到现在。Mobile view的原理大概是这样,当请求到达时,mvc会根据当前应用注册的DisplayMode,然后根据DisplayMode中提供的检测方法检查user agent,如果匹配某种DisplayMode,ViewEngine就会查找带有这种DisplayMode名称后缀的view用来渲染html。

例如,注册了如下的DisplayMode之后,如果user agent中含有"iPhone","iPad"或"Android"就会查找"{ViewName}.mobile.cshtml"的view,而不满足该条件的访问将使用"{ViewName}.cshtml"的视图。

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("mobile")
{
    ContextCondition = (context) => Regex.Match(context.GetOverriddenUserAgent(), @"iPhone|iPad|Android").Success
});

添加mobile view后,view的目录结构变成了这样

其中高亮的两个即为mobile view,配合Jquery mobile,即可简单快捷地提供对移动设备友好的浏览体验。

 

附:MVC4特性

1. Bundling & minification support
    reduce resource file request numbers
    reduce resource file size
    custermizable and extensible to your own process or mimification of resource file
2. Database migrations
    EF code first
    any change can be generated to migration class
    migration rollbackable & can generate to sql script
3. Web APIs
    controller like api service building
    format auto fit
    IQuaryable query via http parameters
    model auto build
    return http information with HttpResponseMessage
    easy to test & host
4. Mobile Web
    Mobile web project
    Mobile view
5. Real time communication
    Persistent connection over HTTP with WebSocket
6. Asynchronous support

 

posted @ 2013-02-25 21:41  傲雪啸风  阅读(823)  评论(0编辑  收藏  举报