我目前正在研究 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/