【问题标题】:How to create TagHelper who's value is a Model Property (without using @Model)?如何创建价值为模型属性的 TagHelper(不使用 @Model)?
【发布时间】:2017-09-03 06:41:57
【问题描述】:

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 表示

asp-for 属性值是一个 ModelExpression 和一个 lambda 表达式的右侧。因此,asp-for="Property1" 在生成的代码中变为 m => m.Property1,这就是为什么您不需要使用 Model 前缀的原因。

所以这很酷,并且相同的文档似乎将其称为“表达式名称”。

如何在我自己的自定义标签助手中创建这样的属性?

【问题讨论】:

    标签: c# asp.net-core-mvc tag-helpers


    【解决方案1】:

    只需在 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>
    

    【讨论】:

    • 整个对象都可以这样做吗?
    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2012-06-14
    相关资源
    最近更新 更多