【问题标题】:Passing custom parameter in custom attribute - ASP.NET MVC在自定义属性中传递自定义参数 - ASP.NET MVC
【发布时间】:2017-02-07 18:53:31
【问题描述】:

我的目标是创建一个自定义属性,例如 System.ComponentModel.DataAnnotations.Display,它允许我传递参数。

例如:在 System.ComponentModel.DataAnnotations.Display 我可以将值传递给参数名称

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

我想做同样的事情,但在控制器和操作中,如下所示

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

然后用其值填充 ViewBag 或 ViewData 项。

我该怎么做?

【问题讨论】:

  • 你必须反思控制器类型,使用GetCustomAttributes使用ViewContext.Controller参考this
  • CustomAttributes 不允许在 ViewBag 或 ViewData 中存储数据
  • 参考this answer,然后将结果赋值给ViewBag

标签: c# asp.net-mvc custom-attributes


【解决方案1】:

这很简单

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"] 一起使用

【讨论】:

  • 非常感谢@Haitham。几分钟前,我使用 BaseController 的 OnActionExecuting 让它工作了。我的修复比你的方法更复杂,所以我正在修改它以作为你的答案。它更优雅。
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多