c# - 在自定义属性中传递自定义参数 - ASP.NET MVC

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

我的目标是创建一个自定义属性,例如 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/

相关文章:

c# - 使用 MVC/MCP 时如何在没有 switch 语句的情况下处理 UI 的派生类?

asp.net-mvc - 如何在 asp.net mvc Controller 中处理 stackoverflow 的问题 url?

c# - TypeBuilder - 添加属性

c# - 如何在一条语句中向SQL命令添加多个参数?

c# - 从 pfx 文件中提取公钥(类似程序集)

c# - 如何解析时区偏移字符串?

c# - TcpListener 常量错误 每个地址只使用一次

asp.net-mvc - 如何将模型传递给局部 View

c# - asp.net MVC自定义Authorize属性,传递参数和方法细节

asp.net - 将自定义属性添加到 asp :CheckBox control