本文介绍了使用asp-for作为参数的自定义ViewComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把它包起来:

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

放入可重用的ViewComponent中,其中的属性将是参数:

into reusable ViewComponent, where property will be parameter:

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

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

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" />

有什么想法吗?

推荐答案

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

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" />

就像@JoelHarkes提到的那样,在这种特殊情况下,自定义taghelper可能更合适.无论如何,我仍然可以在TagHelper中渲染PartialView ala模板:

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

.cshtml模板将与viewcomponent中的外观完全一样.

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

这篇关于使用asp-for作为参数的自定义ViewComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 17:50