c# - 自定义标签助手 : How do I use complex objects in attributes?

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

我目前正在研究 ASP.NET Core 自定义标签助手。我需要从一个属性中读取一个复杂的对象,如下所示:

[模型]

public class Page {
  [HtmlAttributeName(page-size)]
  public int size {get; set;}
}

public class MyControl {
  public Page page {get; set;}
}

[TagHelper 类]

[TargetElement("MyControl", Attributes="page-size")]
public class MyControlTagHelper : TagHelper {
  public Page page {get; set;}
  //Here i have process methods.
}

现在我想在 View 中获取页面大小值,如下所示:

<MyControl page-size="4"></MyControl>

我不知道该怎么做。到目前为止,我尝试将完整的复杂对象提供给属性 as shown in this article .

如何将复杂对象的值读取为 page-size

最佳答案

从 Page 类中删除 HtmlAttributeName

public class Page {
  public int size{ get;set; }
 }

你不需要 MyControl 类

将 HtmlAttributeName 放在标签助手的 PageProperty 上

[TargetElement("MyControl", Attributes="page-info")]
public class MyControlTagHelper : TagHelper {

  [HtmlAttributeName("page-info")]
  public Page page{ get;set; }
 //Here i have process methods.
 }

在您的 View 中放置自定义标记的标记,并从您的 View 模型传入 Page 对象

<MyControl page-info="@Model.Page"></MyControl>

现在您直接在 page-info 属性上传递 Page 对象,您可以直接从 process 方法访问其成员。在 process 方法中测试它是否为 null,如果它是 null,只需设置 output.SuppressOutput();返回;

关于c# - 自定义标签助手 : How do I use complex objects in attributes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246855/

相关文章:

c# - 解释 "finally"在 try-catch-finally block 中的使用

c# - 按 ID 或按类型和语言更新资源的 RESTful 约定

asp.net-core - 带有复选框 bool 值的 Razor 页面处理程序不绑定(bind)

c# - 如何在命令行上更改连接字符串以在迁移到 Entity Framework Core 中的新数据库时更新数据库

azure - 虚拟应用程序的不同应用程序设置/环境变量

c# - ASP.NET 5 MVC 6 中的 TagBuilder InnerHtml

c# - 将流上的编码更改为 UTF-8 (MemoryMappedViewStream)

c# - 选择中的 Entity Framework 条件

asp.net-core - 如何创建一个继承自标准 .Net Core 脚本标签助手的脚本标签助手

c# - .net core mvc 的 Spring boot Autowired 注释等价物