如何从模型值提供标签助手属性
How to supply tag helper attribute from model value
我有一个标签助手,其中包含一个值为枚举的属性:
public class MyElementTagHelper : TagHelper
{
public MyAttribute MyAttribute { get; set; }
}
public attribute MyAttribute { apple, banana, cherry }
这允许我创建一个带有 my-attribute
属性的 HTML <my-element>
标签,如下所示:
<my-element my-attribute="apple">
我的问题是:假设我的视图模型如下所示:
public class MyViewModel
{
public MyAttribute MyAttribute { get; set; }
}
有没有办法使用视图模型中的MyAttribute
值作为HTML属性的值,有点像这样:
<my-element my-attribute="Model.MyAttribute">
更一般地说,有没有办法将变量引用为属性值?
[回答我自己的问题]
只需在引号内加上“@”引入C#变量,像这样:
<my-element my-attribute="@Model.MyAttribute">
(我发布了这个问题,因为我确定这行不通。我很确定我几个月前尝试过这个但没有用。要么我失去了理智 - 一个明显的可能性 - 或者这是最近几个月添加的新内容。)
我有一个标签助手,其中包含一个值为枚举的属性:
public class MyElementTagHelper : TagHelper
{
public MyAttribute MyAttribute { get; set; }
}
public attribute MyAttribute { apple, banana, cherry }
这允许我创建一个带有 my-attribute
属性的 HTML <my-element>
标签,如下所示:
<my-element my-attribute="apple">
我的问题是:假设我的视图模型如下所示:
public class MyViewModel
{
public MyAttribute MyAttribute { get; set; }
}
有没有办法使用视图模型中的MyAttribute
值作为HTML属性的值,有点像这样:
<my-element my-attribute="Model.MyAttribute">
更一般地说,有没有办法将变量引用为属性值?
[回答我自己的问题]
只需在引号内加上“@”引入C#变量,像这样:
<my-element my-attribute="@Model.MyAttribute">
(我发布了这个问题,因为我确定这行不通。我很确定我几个月前尝试过这个但没有用。要么我失去了理智 - 一个明显的可能性 - 或者这是最近几个月添加的新内容。)