asp.net-mvc - 在 Tag Helper 中获取属性名称

标签 asp.net-mvc razor asp.net-core tag-helpers

ASP.NET Core 引入了自定义标签助手,可以在如下 View 中使用:

<country-select value="CountryCode"  />

但是,我不明白如何在我的类中获取模型属性名称:

public class CountrySelectTagHelper : TagHelper
{
    [HtmlAttributeName("value")]
    public string Value { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
       ...
       // Should return property name, which is "CountryCode" in the above example
       var propertyName = ???();  
       base.Process(context, output);
    }
}

在以前的版本中,我可以通过使用 ModelMetadata 来做到这一点:

var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var property = metadata.PropertyName; // return "CountryCode"

我如何在新的 ASP.NET 标签助手中做同样的事情?

最佳答案

为了获取属性名称,您应该在您的类中使用 ModelExpression:

public class CountrySelectTagHelper : TagHelper
{
    public ModelExpression For { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var propertyName = For.Metadata.PropertyName;
        var value = For.Model as string;

        ...

        base.Process(context, output);
    }
}

关于asp.net-mvc - 在 Tag Helper 中获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39200960/

相关文章:

javascript - 如何在我的代码中切换类,我做错了什么?

angularjs - ASP.NET 5 中的 URL 重写

mono - 使用单声道挂起的 Travis 上的 dnx 测试

asp.net-mvc - MVC4 Razor View 中出现奇怪的空白

javascript - 无论如何都不能读得不引人注目

c# - URL 中的隐藏参数

c# - 按钮 Onclick 事件(在 codbehind 中)不会在 MVC 2 中触发

c# - 从 foreach 循环中将模型加载到局部 View 中

c# - ASP.NET-Core 嵌套 ASP TagHelper

asp.net - 在 Azure SQL 上打开 DataReader 错误,但在 SQL Server 2014 上却没有