使用asp-for作为参数的自定义ViewComponent

时间:2017-03-17 11:00:17

标签: c# asp.net-core asp.net-core-viewcomponent

我想包装这个:

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

进入可重用的ViewComponent,其中property属性为参数:

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

我能够将asp-for参数传递给viewcomponent:

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

但是我无法在组件的视图中对其进行评估。这不起作用:

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

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我认为你正在混合ViewComponents和TagHelpers:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components

查看组件

在以下事项中调用视图组件:

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

尝试以下snippit:

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

Taghelpers

标签助手只能这样调用:

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

答案 1 :(得分:1)

如果要将ModelExpression传递给基础ViewComponent,然后将其传递给TagHelper,则必须使用@TheModelExpression.Model执行此操作:

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

正如@JoelHarkes所提到的,在这种特殊情况下,自定义taghelper可能更合适。无论如何,我仍然可以在TagHelper中渲染PartialView ala Template:

[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());
    }
}

然后.cshtml模板看起来与viewcomponent完全相同。