mikal
mikal

Reputation: 1345

Asp.Net 5 TagHelper Modelstate binding

I'm trying to make a custom TagHelper that binds to the current ModelState, much like

<input asp-for="this_part" />

I would like to do some ModelState verification from my custom TagHelper-class.

Tried to search the Github repository, but couldn't pinpoint this exact behavior. Anyone found a way to do this?

Thanks!

Upvotes: 1

Views: 1415

Answers (1)

Matt DeKrey
Matt DeKrey

Reputation: 11942

I'm not sure exactly what you're looking for, but the DefaultHtmlGenerator does something similar for validation messages.

You can access the ModelState via the ViewContext (Sample adapted from ValidationMessageTagHelper.cs):

[TargetElement("span", Attributes = AttributeName)]
public class YourTagHelper : TagHelper
{
    private const string AttributeName = "your-for";

    [ViewContext]
    [HtmlAttributeNotBound]
    protected internal ViewContext ViewContext { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        var modelState = ViewContext.ViewData.ModelState;
        // Your logic here
    }
}

From your comments, you mentioned that you wanted intellisense for mapping to a Model property. ValidationMessageTagHelper.cs does this with this property:

[HtmlAttributeName(ValidationForAttributeName)]
public ModelExpression For { get; set; }

Upvotes: 5

Related Questions