1

目前,我有一个桌面应用程序,它的一些视图可用于移动设备。我添加了在桌面版和移动版之间切换的功能。但是,如果用户在一个没有移动版的页面上并切换到移动版,就会发生一堆坏事......有没有办法告诉 MVC4 去一个“对不起,这不是在如果当前视图的移动版本不存在,则为 Mobile yet”页面?

谢谢!

4

1 回答 1

1

这就是我最终做的。我创建了一个 HasMobileVersion 属性来装饰所有具有相应移动版本的 View 方法。我没有显示“抱歉”页面,而是将用户重定向到根 URL(移动版本必须存在那里)。这是它的代码:

/// <summary>
/// This attribute specifies which views have Mobile versions available.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HasMobileVersionAttribute : ActionFilterAttribute
{

    #region << Constructors >>

    /// <summary>
    /// Default constructor.
    /// </summary>
    public HasMobileVersionAttribute()
    {
        // Nothing to do
    }

    #endregion

    #region << Overridden Methods >>

    /// <summary>
    /// Allows a View to switch between mobile and desktop versions, ensuring that if a page does not have a mobile version that
    /// it sends the user to the root page.
    /// </summary>
    /// <param name="ac">Request data.</param>
    public override void OnActionExecuting(ActionExecutingContext ac)
    {
        ac.Controller.ViewBag.HasMobileVersion = true;
    }

    #endregion

}

我们声明了一个链接(好吧,图标),允许用户在移动设备和桌面设备之间切换。此链接将从 ViewBag 中检查 HasMobileVersion == true。如果是,一旦用户处于移动模式,它将使用当前 URL 作为返回 URL。如果这不存在,那么我们强制移动链接将使用的返回 URL 作为站点“/”的根。您必须竭尽全力装饰所有具有移动页面的视图,但效果很好。

编辑:

为了在移动/桌面之间切换,我们有一个 ViewSwitcher 控制器。如果您在_Layout,显然您将切换到Mobile版本。如果您在 _Layout.Mobile 中,您将转到桌面。该属性仅用于确定当前页面是否有可供查看的移动版本。在移动端,桌面版本始终存在(否则,您也必须创建 HasDesktopVersion 属性)。这是该代码:

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

public class ViewSwitcherController : Controller
{

    #region << Views >>

    /// <summary>
    /// Allows the user to swicth between mobile and desktop versions of the site.
    /// </summary>
    /// <param name="mobile">True if the user should view the mobile version; false if the user should view the desktop version.</param>
    /// <param name="returnUrl">Original URL.</param>
    /// <returns>RedirectResult to original URL.</returns>
    public RedirectResult SwitchView(bool mobile, string returnUrl)
    {
        if (Request.Browser.IsMobileDevice == mobile)
            HttpContext.ClearOverriddenBrowser();
        else
            HttpContext.SetOverriddenBrowser(mobile ? BrowserOverride.Mobile : BrowserOverride.Desktop);

        return Redirect(returnUrl);
    }

    #endregion

}

这是获取讨论结果的 URL 的 Razor:

@Url.Action("SwitchView", "ViewSwitcher" , new { mobile = true, returnUrl = ViewBag.HasMobileVersion != null && ViewBag.HasMobileVersion ? Request.Url.PathAndQuery : "/" })

在移动端,mobile 将 = false。

于 2012-10-10T15:08:14.423 回答