在自定义属性中传递自定义参数 - ASP.NET MVC
Passing custom parameter in custom attribute - ASP.NET MVC
我的目标是创建一个像 System.ComponentModel.DataAnnotations.Display 这样的自定义属性,它允许我传递参数。
例如:在System.ComponentModel.DataAnnotations.Display中我可以传递一个值给参数Name
[Display(Name = "PropertyName")]
public int Property { get; set; }
我想做同样的事情,但在如下所示的控制器和操作中
[CustomDisplay(Name = "Controller name")]
public class HomeController : Controller
然后用它的值填充 ViewBag 或 ViewData 项。
我该怎么做?
这个很简单
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"]
一起使用
我的目标是创建一个像 System.ComponentModel.DataAnnotations.Display 这样的自定义属性,它允许我传递参数。
例如:在System.ComponentModel.DataAnnotations.Display中我可以传递一个值给参数Name
[Display(Name = "PropertyName")]
public int Property { get; set; }
我想做同样的事情,但在如下所示的控制器和操作中
[CustomDisplay(Name = "Controller name")]
public class HomeController : Controller
然后用它的值填充 ViewBag 或 ViewData 项。
我该怎么做?
这个很简单
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"]