Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve asp-for in custom tag helper

I have a lot of Bootstrap inputs in my edit forms and I'm using the asp-for tag helper for model binding.

                <div class="form-group">
                    <div class="fg-line">
                        <label asp-for="@Model.Name" class="control-label"></label>
                        <input asp-for="@Model.Name" class="form-control"/>
                    </div>
                    <span asp-validation-for="@Model.Name" class="help-block"></span>
                </div>

I want to write a custom tag helper, so that I can write:

<bsinput asp-for="@Model.Name" /> 

...which produces the output above.

Is it possible to evaluate nested tag helpers?

like image 548
Jetro223 Avatar asked Mar 24 '16 10:03

Jetro223


1 Answers

I stumbled upon this question while doing some research on the same problem. This is how I resolved the problem for me :

In my case I have a colour picker that is generated with my custom tag helper. This is my class :

public class ColourPickerTagHelper : TagHelper
{
    public ModelExpression AspFor { get; set; }
    public List<CustomSelectItem> AspColours { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "select";
        string name = this.AspFor.Name;
        if (!String.IsNullOrEmpty(name))
        {
            output.Attributes.Add("name", name);
        }
        output.Content.SetHtmlContent(LoadMyOptions());
        output.TagMode = TagMode.StartTagAndEndTag;
    }
}

And I call it like this :

<colour-picker asp-for="Form.Colour" asp-colours="Model.MyOptions" />

EDIT : I updated my answer since I found out about the ModelExpression object.

like image 180
attacksquid Avatar answered Sep 18 '22 01:09

attacksquid