How to adapt layouts and views for different browsers in ASP. NET MVC 4

Source: Internet
Author: User

In ASP. 4, you can easily implement adaptive layouts and views for different browsers. This is due to the design concept of "convention over configuration" in MVC.

Default self-adapting

MVC 4 automatically adapts to mobile device browsers and PC device browsers. For the layout page, the default file name is _layout.cshtml, which is used by all browsers. But if we want to present a different layout on the mobile device, we just need to add a layout page called _layout.mobile.cshtml. The same rules apply to normal view pages as well. For example, index.cshtml is used by all browsers by default, but if Index.Mobile.cshtml is added, the new view is automatically rendered on top of the mobile device. As shown

So why is it possible to automate such a function? Or we should ask, how can we differentiate between mobile browsers? Actually, this is not hard to say.

The following article describes some of the basic concepts of browser detection HTTP://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/X3K2SSX2 (v=vs.100). aspx

In ASP. Where, in what way, is the detection done, and the layout or view is chosen accordingly?

By analyzing the source code (http://aspnetwebstack.codeplex.com/), we can find clues in the following code

So, this feature is implemented in the Displaymodeprovider type. It registers a default of two so-called Defaultdisplaymode, the first of which is conditional judgment, according to the IsMobileDevice attribute is not a mobile device browser, if yes, then use a fixed prefix mobile. This defaultdisplaymode type will automatically do the transform of the path.

?

Custom adaptation Rules

?

If we understand the above principles, we can add our own rules as needed. For example, we can add a specific display model to the iphone device and modify the code in the Global.asax.

?

This way, you can simply add the following layout or view page to your iphone device.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.