I am currently working on an ASP.NET Core custom tag helper. 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]
[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
?
HtmlHelpers vs. Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.
The Input Tag Helper binds an HTML <input> element to a model expression in your razor view. The Input Tag Helper: Generates the id and name HTML attributes for the expression name specified in the asp-for attribute. asp-for="Property1.
Using HtmlTargetElement attribute, we can provide a tag helper target. It passes an attribute parameter that specifies the HTML element which contains an HTML attribute named, for example, "my-first-tag-helper". It will match and process the override method in the class it will run.
@addTagHelper makes Tag Helpers available The code above uses the wildcard syntax ("*") to specify that all Tag Helpers in the specified assembly (Microsoft. AspNetCore. Mvc. TagHelpers) will be available to every view file in the Views directory or subdirectory.
Remove the HtmlAttributeName from Page class
public class Page {
public int size{ get;set; }
}
you don't need MyControl class
put the HtmlAttributeName on the PageProperty of your taghelper
[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
<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. Do test it for null inside the process method and if it is null just set output.SuppressOutput(); return;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With