Tag Helper是Asp.Net核心的可爱特性之一。我已经创建了几个标签助手,它们可以非常有用。
现在我想尝试一些更先进的东西。标记助手属性具有创建的能力,例如属性值是一个模型属性。
这方面的例子如下:
//model
public class MyModel{
public int MyField {get;set;} = 10;
}
//in the view
@model MyModel
...
<input asp-for="MyField" />在上面的示例中,指向asp-for标记的input标记助手引用了模型中的一个属性。文档说
asp-for属性值是lambda表达式的ModelExpression和右侧。因此,asp-for="Property1“在生成的代码中变成m => m.Property1,这就是为什么您不需要使用Model前缀的原因。
因此,这是相当酷的,同样的文档似乎称之为“表达式名称”。
如何在自己的自定义标记助手中创建这样的属性?
发布于 2017-04-08 10:56:37
只需将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>https://stackoverflow.com/questions/43285590
复制相似问题