Asp.Net MVC:現在のコントローラー/ビューの仮想URLを取得するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/151963

  •  02-07-2019
  •  | 
  •  

質問

コントローラーアクションまたはビューに関連付けられたルート/仮想URLを取得することは可能ですか? Preview 4にLinkBuilder.BuildUrlFromExpressionヘルパーが追加されたのを見ましたが、マスターで使用したい場合、コントローラーのタイプが異なる可能性があるため、あまり役に立ちません。どんな考えでも大歓迎です。

役に立ちましたか?

解決 3

そのデータはViewContext.RouteDataから取得できます。以下に、その情報にアクセス(および使用)する方法の例を示します。

///これらは、viewmasterpage、viewpage、viewusercontrolの基本クラスに追加されます。

public bool IsController(string controller)
{
    if (ViewContext.RouteData.Values["controller"] != null)
    {
        return ViewContext.RouteData.Values["controller"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);
    }
    return false;
}
public bool IsAction(string action)
{
    if (ViewContext.RouteData.Values["action"] != null)
    {
        return ViewContext.RouteData.Values["action"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);
    }
    return false;
}
public bool IsAction(string action, string controller)
{
    return IsController(controller) && IsAction(action);
}

/// UrlHelperクラスに追加したいくつかの拡張メソッド。

public static class UrlHelperExtensions
{
    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">Url Helper</param>
    /// <param name="action">The action to check.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
    {
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
        {
            throw new ArgumentException("Expression must be a method call", "action");
        }

        return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
                typeof(TController) == helper.ViewContext.Controller.GetType());
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
        return IsAction(helper, actionName, controllerName);
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <param name="controllerName">Name of the controller.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        if (String.IsNullOrEmpty(controllerName))
        {
            throw new ArgumentException("Please specify the name of the controller", "controllerName");
        }

        if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName + "Controller";
        }

        bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
        return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// Determines if the current request is on the specified controller
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="controllerName">Name of the controller.</param>
    /// <returns>
    ///     <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsController(this UrlHelper helper, string controllerName)
    {
        if (String.IsNullOrEmpty(controllerName))
        {
            throw new ArgumentException("Please specify the name of the controller", "controllerName");
        }

        if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName + "Controller";
        }

        return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// Determines if the current request is on the specified controller
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">The helper.</param>
    /// <returns>
    ///     <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsController<TController>(this UrlHelper helper) where TController : Controller
    {
        return (typeof(TController) == helper.ViewContext.Controller.GetType());
    }
}

他のヒント

私は常に、プロジェクトの要件を満たす最も簡単なソリューションを実装しようとしています。エンスタインが言ったように、<!> quot;できる限りシンプルに、しかし単純ではないものにします。<!> quot;これを試して。

<%: Request.Path %>

これは私のために働いた:

<%= this.Url.RouteUrl(this.ViewContext.RouteData.Values) %>

現在のUrlを返します。 /Home/About

実際のルート文字列を返すより簡単な方法があるかもしれませんか?

<!> lt;%= Url.Action(action、controller、values)%<!> gt;を使用できます。マスターページ内からURLを作成します。

現在のページまたは何かのタブをハイライトするためにこれを行っていますか?

その場合、ビューからViewContextを使用して、必要な値を取得できます。

ヘルパークラスを作成しました。ルートパラメータにアクセスします。このヘルパーを使用すると、コントローラー、アクション、およびアクションに渡されるすべてのパラメーターを取得できます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top