在自定义属性中传递自定义参数-ASP.NET MVC [英] Passing custom parameter in custom attribute - ASP.NET MVC

查看:180
本文介绍了在自定义属性中传递自定义参数-ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My goal is to create a custom attribute like System.ComponentModel.DataAnnotations.Display which allows me to pass a parameter.

例如:在System.ComponentModel.DataAnnotations.Display中,我可以将值传递给参数Name

Ex.: In System.ComponentModel.DataAnnotations.Display I can pass a value to the parameter Name

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

我想做同样的事情,但是要在类似下面的控制器和动作中

I want to do the same but in controllers and actions like below

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

,然后用其值填充ViewBag或ViewData项目.

and then fill a ViewBag or ViewData item with its value.

我该怎么做?

推荐答案

这很简单

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);
    }
}

然后您可以按如下所示在控制器中使用它

Then you can use it in your controller as below

[ControllerDisplayName(Name ="My Account Contolller"])
public class AccountController : Controller
{
}

在您的视图中,您可以自动将其与@ViewData["ControllerDisplayName"]

And in your view you can automatically use it with @ViewData["ControllerDisplayName"]

这篇关于在自定义属性中传递自定义参数-ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆