2016-09-29 160 views
3

我的目標是創建一個自定義屬性,如System.ComponentModel.DataAnnotations.Display,它允許我傳遞一個參數。在自定義屬性中傳遞自定義參數 - ASP.NET MVC

例:在System.ComponentModel.DataAnnotations.Display我可以將值傳遞給參數名稱

[Display(Name = "PropertyName")] 
public int Property { get; set; } 

我想要做相同的,但在控制器和動作像下面

[CustomDisplay(Name = "Controller name")] 
public class HomeController : Controller 

,然後用它的值填充ViewBag或ViewData項目。

有人可以幫助我嗎?

謝謝。

+1

使用,則必須反映在控制器類型上,使用['GetCustomAttributes'](https://msdn.microsoft.com/en-us/library/dwc6ew1d.aspx)使用'ViewContext.Controller'請參閱[this](http://stackoverflow.com /題s/19412483/mvc3-can-you-give-controller-a-display-name) –

+0

CustomAttributes不允許存儲數據在ViewBag或ViewData中 –

+1

參考[this answer](http://stackoverflow.com/questions/2656189/how -do-i-read-an-attribute-on-a-class-at-runtime),然後將結果賦給'ViewBag' –

回答

4

這是非常簡單的

public class ControllerDisplayNameAttribute : ActionFilterAttribute 
{ 
    public string Name { get; set; } 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     string name = Name; 
     if (string.IsNullOrEmpty(name)) 
      name = filterContext.Controller.GetType().Name; 

     filterContext.Controller.ViewData["ControllerDisplayName"] = Name; 
     base.OnActionExecuting(filterContext); 
    } 
} 

然後你可以使用它在你的控制器,如下

[ControllerDisplayName(Name ="My Account Contolller"]) 
public class AccountController : Controller 
{ 
} 

而且在你看來,你可以自動@ViewData["ControllerDisplayName"]

+0

非常感謝@Haitham。幾分鐘前,我得到它使用OnActionExecuting我的BaseController。我的修復比你的修復更復雜,所以我修改它以作爲你的答案。它更優雅。 –