简体   繁体   English

自定义标签助手:如何在属性中使用复杂对象?

[英]Custom tag helper: How do I use complex objects in attributes?

I am currently working on an ASP.NET Core custom tag helper.我目前正在研究 ASP.NET Core 自定义标记助手。 I need to read a complex object from an attribute as follows:我需要从属性中读取一个复杂的对象,如下所示:

[Models] [楷模]

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

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

[TagHelper class] [TagHelper 类]

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

And now I want to get the page size value in the view as follows:现在我想在视图中获取页面大小值,如下所示:

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

I don't know to do this.我不知道要这样做。 So far, I tried to provide the full complex object to an attribute as shown in this article .到目前为止,我尝试为属性提供完整的复杂对象, 如本文所示

How can I read the complex object's values as page-size ?如何将复杂对象的值读取为page-size

Remove the HtmlAttributeName from Page class从 Page 类中删除 HtmlAttributeName

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

you don't need MyControl class你不需要 MyControl 类

put the HtmlAttributeName on the PageProperty of your taghelper将 HtmlAttributeName 放在 taghelper 的 PageProperty 上

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

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

in your view put the markup for your custom tag and pass in the Page object from your viewmodel在您的视图中放置自定义标签的标记并从您的视图模型中传入 Page 对象

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

now you are passing in the Page object directly on the page-info attribute and you can access its members directly from the process method.现在您直接在 page-info 属性上传入 Page 对象,您可以直接从 process 方法访问其成员。 Do test it for null inside the process method and if it is null just set output.SuppressOutput();在 process 方法中测试它是否为 null,如果它为 null 只需设置 output.SuppressOutput(); return;返回;

Your tag helper class should be as follows:您的标签助手类应如下所示:

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

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

}

And your view page as follows:您的查看页面如下:

<MyControl page-info="new Page{size = 2}"></MyControl>

For further reference:进一步参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM