技术开发 频道

使用ASP.NET MVC检测、重定向移动设备

  清单:Controllers\MobileController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MVCMobileDetect.Controllers
{
    
public class MobileController : Controller
    {
        
//
        
// GET: /Mobile/
        public ActionResult Index()
        {
            
return View();
        }

        
public ActionResult Nokia()
        {
            
return View();
        }

        
public ActionResult Iphone()
        {
            
return View();
        }

        
public ActionResult Blackberry()
        {
            
return View();
        }
    }
}

  现在,我们需要根据设备是否为移动设备来让ASP.NET MVC查找不同的视图。为了装入为移动设备优化过的视图,需要向HomeController.cs添加下列代码。

  清单:Controllers\HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCMobileDetect.Controllers
{
    [HandleError]
    
public class HomeController : Controller
    {
        
public ActionResult Index()
        {
            ViewData[
"Message"] = "Welcome to ASP.NET MVC!";
            
if (Request.Browser.IsMobileDevice)
            {
                
string strmanu = Request.Browser.MobileDeviceManufacturer.ToLower().ToString();
                
string straction = "";
                
string strcontrol = "Mobile";
                
switch (strmanu)
                {
                    
case "nokia":
                        straction
= "Nokia";
                        
break;
                    
case "rim":
                        straction
= "Blackberry";
                        
break;
                    
case "apple":
                        straction
= "Iphone";
                        
break;
                    
default:
                        straction
= "Index";
                        
break;
                }
                
return RedirectToAction(straction, strcontrol);
            }
            
else
                
return View();
        }

        
public ActionResult About()
        {
            
return View();
        }

   步骤5:创建ASP.NET MVC视图

  MobileController.cs中的Index()方法将返回一个名为Index的视图,该视图位于Views->Mobile文件夹中。我们需要为Nokia、Iphone和Blackberry之外的移动设备创建这个视图。

  具体可参照以下步骤:

  (1)在代码编辑器中右键单击Index()方法,并选择菜单选项Add View(参见图08)。

  (2)在Add View对话框中,不要选择任何复选框(参见图09)。


图8 从控制器动作中添加一个视图


图9 利用Add View对话框创建新视图

  完成上述步骤之后,一个名为Index.aspx的新视图将添加到Views\Mobile文件夹。对于Nokia()、Iphone()和Blackberry(),可以执行同样的步骤来创建视图(参见图10)。


图10 Views->Mobile文件夹结构

0
相关文章