如何创建值为 Model 属性 的 TagHelper(不使用 @Model)?
How to create TagHelper who's value is a Model Property (without using @Model)?
Tag Helper 是 Asp.Net Core 的一项重要功能。我创建了几个标签助手,它们非常有用。
现在我想尝试一些更高级的东西。标签助手属性能够以属性值是模型 属性 的方式创建。
例子如下:
//model
public class MyModel{
public int MyField {get;set;} = 10;
}
//in the view
@model MyModel
...
<input asp-for="MyField" />
在上面的示例中,input
标记的 asp-for
标记助手直接引用了模型中的 属性。 documentation 表示
The asp-for attribute value is a ModelExpression and the right hand side of a lambda expression. Therefore, asp-for="Property1" becomes m => m.Property1 in the generated code which is why you don't need to prefix with Model.
所以这很酷,同一份文档似乎将其称为 "Expression name"。
如何在我自己的自定义标签助手中创建这样的 属性?
只需在 TagHelper 中将参数声明为 ModelExpression
类型,然后使用它来生成内容。
例如:
public class FooTagHelper : TagHelper
{
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.Content.SetHtmlContent(
$@"You want the value of property <strong>{For.Name}</strong>
which is <strong>{For.Model}</strong>");
}
}
如果您在这样的视图中使用它:
@model TestModel
<foo for="Id"></foo>
<foo for="Val"></foo>
并传递像 new TestModel { Id = "123", Val = "some value" }
这样的模型,然后您将在视图中获得以下输出(为清楚起见格式化):
<div>
You want the value of property <strong>Id</strong>
which is <strong>123</strong>
</div>
<div>
You want the value of property <strong>Val</strong>
which is <strong>some value</strong>
</div>
Tag Helper 是 Asp.Net Core 的一项重要功能。我创建了几个标签助手,它们非常有用。
现在我想尝试一些更高级的东西。标签助手属性能够以属性值是模型 属性 的方式创建。
例子如下:
//model
public class MyModel{
public int MyField {get;set;} = 10;
}
//in the view
@model MyModel
...
<input asp-for="MyField" />
在上面的示例中,input
标记的 asp-for
标记助手直接引用了模型中的 属性。 documentation 表示
The asp-for attribute value is a ModelExpression and the right hand side of a lambda expression. Therefore, asp-for="Property1" becomes m => m.Property1 in the generated code which is why you don't need to prefix with Model.
所以这很酷,同一份文档似乎将其称为 "Expression name"。
如何在我自己的自定义标签助手中创建这样的 属性?
只需在 TagHelper 中将参数声明为 ModelExpression
类型,然后使用它来生成内容。
例如:
public class FooTagHelper : TagHelper
{
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div";
output.Content.SetHtmlContent(
$@"You want the value of property <strong>{For.Name}</strong>
which is <strong>{For.Model}</strong>");
}
}
如果您在这样的视图中使用它:
@model TestModel
<foo for="Id"></foo>
<foo for="Val"></foo>
并传递像 new TestModel { Id = "123", Val = "some value" }
这样的模型,然后您将在视图中获得以下输出(为清楚起见格式化):
<div>
You want the value of property <strong>Id</strong>
which is <strong>123</strong>
</div>
<div>
You want the value of property <strong>Val</strong>
which is <strong>some value</strong>
</div>