Custom ViewComponent with asp-for as parameter

怎甘沉沦 提交于 2020-01-31 05:03:05

问题


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.



来源:https://stackoverflow.com/questions/42855758/custom-viewcomponent-with-asp-for-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!