我的目标是创建一个自定义属性,例如 System.ComponentModel.DataAnnotations.Display,它允许我传递参数。
例如:在 System.ComponentModel.DataAnnotations.Display 中,我可以将值传递给参数名称
[Display(Name = "PropertyName")]
public int Property { get; set; }
我想做同样的事情,但在如下 Controller 和操作中
[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);
}
}
然后你可以在你的 Controller 中使用它,如下所示
[ControllerDisplayName(Name ="My Account Contolller"])
public class AccountController : Controller
{
}
并且在您的 View 中,您可以自动将它与 @ViewData["ControllerDisplayName"]
一起使用
关于c# - 在自定义属性中传递自定义参数 - ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770432/