Custom tag helper: How do I use complex objects in attributes?
Asked Answered
A

2

5

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?

Abatement answered 6/7, 2015 at 13:13 Comment(0)
M
7

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;

Mazdaism answered 6/7, 2015 at 21:0 Comment(3)
Thanks for the answer. But i want to get the values for each property in complex object individually. is it possible?Abatement
if you want them individually then you should create properties for each setting on the taghelper and pass them in individually as attributes in your view. You can either pass in a complex object or multiple simple primitive types but you cannot pass in a complex object and have it magically map to separate primitives as far as I know. Seems much cleaner to just pass in the complex object and then access its properties individually like page.size etcMazdaism
It works to passing complex object in tag helper (asp net core 2), this answer must be flagged to accepted.Lucretialucretius
A
3

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:

Afrikah answered 8/7, 2015 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.