2011-01-07 81 views
1

我使用兩個單獨的頁面的局部視圖和局部視圖使用元數據來獲得對模型屬性的形式顯示名稱(執行元數據的標準方式行動)。MVC2發現面積/控制器/自定義屬性中

我需要根據網頁上的顯示名稱上下文敏感的。

爲此,我擴展了System.ComponentModel.DisplayNameAttribute,並傳入一個area/controller/action/resourcefile/resourcestring數組,以便根據上下文選擇正確的資源字符串。

我的問題是如何獲得的面積/控制器/動作從內執行以下操作:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using CommonInterfaces.Helpers; 

namespace CommonInterfaces.ComponentModel 
{ 
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 
    public class ContextSensitiveDisplayName : System.ComponentModel.DisplayNameAttribute 
    { 
     public class Context 
     { 
      public string Area { get; set; } 
      public string Controller { get; set; } 
      public string Action { get; set; } 
      public Type ResourceType { get; set; } 
      public string ResourceKey { get; set; } 

      public Context(string area, string controller, string action, Type resourceType, string resourceKey) 
      { 
       this.Area = area; 
       this.Controller = controller; 
       this.Action = action; 
       this.ResourceType = resourceType; 
       this.ResourceKey = resourceKey; 
      } 
     } 

     public ContextSensitiveDisplayName(params Context[] contexts) 
     { 
      /* Its these values that I need */ 
      string currentArea = ""; 
      string currentController = ""; 
      string currentAction = ""; 

      Context selectedContext = 
       contexts.FirstOrDefault(m => 
        (m.Area == currentArea) && 
        (m.Controller == currentController) && 
        (m.Action == currentAction) 
       ); 

      this.DisplayNameValue = ""; // Use the selectContext to retrieve string from resource file. 
     } 
    } 
} 

任何幫助,這將不勝感激。

回答

1

我到底用這個。

var routingValues = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)).Values; 
    string currentArea = (string)routingValues["area"] ?? string.Empty; 
    string currentController = (string)routingValues["controller"] ?? string.Empty; 
    string currentAction = (string)routingValues["action"] ?? string.Empty; 

我要去嘗試的Jakub Konecki的答案之前,我作爲一個正確的馬克 - 他看起來多了幾分穩健與null檢查和所有。我很快就會到這裏來。

-1

你不知道。屬性實例不是在知道路由的上下文中創建的。你不能在屬性中做到這一點。

這也不是信息通過DefaultModelBinder傳遞到元數據提供商,所以寫一個自定義的元數據提供商不會幫助,除非你也寫了自定義模型粘合劑。這是工作太多恕我直言。

我建議使用不同的視圖模型。

+0

我已經標記了這個,因爲你可以很容易地得到路由信息。 – 2011-01-14 11:06:21

1

這是一個有點討厭,但應該工作:

if(HttpContext.Current != null && HttpContext.Current.Handler is System.Web.Mvc.MvcHandler) 
{ 
    var handler = HttpContext.Current.Handler as System.Web.Mvc.MvcHandler; 
    var controller = handler.RequestContext.RouteData.Values["controller"]; 
    var action = handler.RequestContext.RouteData.Values["action"]; 
} 
+0

嗯,我同意這個「討厭」的部分。 :) – 2011-01-14 15:46:34