Custom ViewComponent with asp-for as parameter

2019-03-27 05:27发布

问题:

I want wrap this:

<textarea asp-for="@Model.Content" ...>

into reusable ViewComponent, where property will be parameter:

<vc:editor asp-for="@Model.Content" />

I was able to pass asp-for as parameter to the viewcomponent:

public class EditorViewComponent : ViewComponent
{
    public IViewComponentResult Invoke(ModelExpression aspFor = null)
    {
        //when debugging, aspFor has correct value
        return View(aspFor);
    }
}

But I'm not able to evaluate it in component's view. This does not work:

<!-- ViewComponents/Editor/Default.cshtml -->
@model Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression
<textarea asp-for="@Model" />

Any ideas?

回答1:

I think you are mixing ViewComponents and TagHelpers:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components

View components

View components are invoked in the following matter:

@await Component.InvokeAsync("EditorView", @Model.Property);
// or
<vc:[view-component-name]>

Try the following snippit:

<vc:editor for="@Model.Content" />

Taghelpers

the tag helpers are only invoked like this:

<textarea asp-for="@Model.Content">


回答2:

If you want to pass ModelExpression to underlying ViewComponent and then pass it to TagHelper, you have to do it using @TheModelExpression.Model:

<!-- ViewComponents/Editor/Default.cshtml -->
@model Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression
<textarea asp-for="@Model.Model" />

As @JoelHarkes mentioned, in this particular case, custom taghelper could be more appropriate. Anyway, I still can render PartialView ala Template in the TagHelper:

[HtmlTargetElement("editor", Attributes = "asp-for", TagStructure = TagStructure.WithoutEndTag)]
public class EditorTagHelper : TagHelper
{
    private HtmlHelper _htmlHelper;
    private HtmlEncoder _htmlEncoder;

    public EditorTagHelper(IHtmlHelper htmlHelper, HtmlEncoder htmlEncoder)
    {
        _htmlHelper = htmlHelper as HtmlHelper;
        _htmlEncoder = htmlEncoder;
    }

    [HtmlAttributeName("asp-for")]
    public ModelExpression For { get; set; }

    [ViewContext]
    public ViewContext ViewContext
    {
        set => _htmlHelper.Contextualize(value);
    }


    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = null;

        var partialView = await _htmlHelper.PartialAsync("TagHelpers/Editor", For);

        var writer = new StringWriter();
        partialView.WriteTo(writer, _htmlEncoder);

        output.Content.SetHtmlContent(writer.ToString());
    }
}

the .cshtml template would then look exactly like in viewcomponent.