Reputation: 51000
I have a correctly working tag helper for the <select>
element which contains the following working code:
TagHelperAttribute forAttribute;
if (!context.AllAttributes.TryGetAttribute("asp-for", out forAttribute))
{
throw new Exception("No asp-for attribute found.");
}
var forInfo = (Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression)forAttribute.Value;
I have the same code in a different tag helper, for a novel element I'm calling <date-picker>
. In this second tag helper, the cast to ModelExpression
fails because forAttribute.Value
is, in fact, not a ModelExpression
but rather a string (it is the property name, "DueDate", to which I'm trying to bind the tag).
It seems my novel date-picker
tag is not aware that the asp-for
value should be applied to the Razor page model.
How can I ensure that my date-picker
receives a correct ModelExpression
on which to base my output?
Upvotes: 0
Views: 1246
Reputation: 1
create the attribute TAG and property as shown below:
[HtmlAttributeName("asp-for")]
public ModelExpression AspFor { get; set; }
Access the attribute model value,name etc. as in the following way:
AspFor.Name
AspFor.Model
Upvotes: 0
Reputation: 14482
To ensure your attribute has the proper binding, you need to define a property in your tag helper class, with the HtmlAttributeName
attribute. For example:
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
The reason why the attribute is required is that the HtmlAttributeNameAttribute
class does a lot behind the scene to bind the proper value. You can see how the value is bound on github.
Also, this simplifies how you access the value of the attribute, as you don't need to go through the entire list. So instead of this:
TagHelperAttribute forAttribute;
if (!context.AllAttributes.TryGetAttribute("asp-for", out forAttribute))
{
throw new Exception("No asp-for attribute found.");
}
var forInfo = (Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression)forAttribute.Value;
You can write :
// you can call the For property
var forInfo = For;
Upvotes: 1