我的目标是创建一个自定义属性,如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项。
有人可以帮我这个吗?
感谢。
答案 0 :(得分:7)
这很简单
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"]