在Tag Helper中获取属性名称



ASP。NET Core引入了自定义标记助手,可以在以下视图中使用:

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

您可以通过标记助手属性传递字符串。

 <country-select value="@Model.CountryCode"  />

Razor将通过在@前面加上值Model.CountryCode来填充Value属性。因此,您可以直接获得值,而无需传递模型属性的名称,然后再访问该名称。

我不确定你是否得到了你想要的。如果你想把完整的模型从视图传递给自定义标签助手,我就是这样做的

您可以使用任何自定义属性从视图传入当前模型。请参阅下面的示例。假设您的型号是Country

public class Country
{
    public string Name { get; set; }
    public string Code { get; set; }
}

现在在相同类型的自定义标记帮助程序中声明一个属性。

public Country CountryModel { get; set; }

你的控制器看起来像这个

public IActionResult Index()
{
    var country= new Country
    {
        Name = "United States",
        Code = "USA"
    };
    return View("Generic", country);
}

在这个设置中,要访问taghelper中的模型,只需像任何其他自定义属性/属性一样传入即可

你的视图现在应该看起来像这个

<country-select country-model="@Model"></country-select>

你可以像任何其他类属性一样在你的标签助手中接收它

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

编码快乐!

最新更新