【问题标题】:How to pass csHtml to ViewComponent in .Net Core MVC?如何在 .Net Core MVC 中将 csHtml 传递给 ViewComponent?
【发布时间】:2019-12-31 23:06:57
【问题描述】:

我想像这样将 csHtml 传递给 ViewComponent:

<vc:some-component title="Title" 
body="@Html.Raw("<div>this is a nice div, my name is @Model.Name</div>")">
</vc:some-component>

如您所见,我想传递包含对变量或模型的引用的 HTML(这就是为什么我称它为 csHtml 而不仅仅是 Html)。

这里是 ViewComponent 代码:

<div>
    <p>@Model.Title</p>
    @Model.Content
</div>

这甚至可能吗?我一直在搜索,但没有找到任何有关如何执行此操作的示例。


编辑:搞定了!感谢大家的帮助。

以下是一些示例代码:

调用 ViewComponent:

@{
    Func<dynamic, object> children =
    @<div>
        <p style="color: white">aaaa</p>
        <p style="color: white">bbbb</p>
        <p style="color: white">bbbb</p>
    </div>;
}

<vc:some-component body=@children>
</vc:some-component>

查看组件内容:

@model SomeComponentModel

<div>
    @Model.Body("")
</div>

【问题讨论】:

    标签: asp.net asp.net-core .net-core asp.net-core-2.0 asp.net-core-viewcomponent


    【解决方案1】:

    您应该能够将参数添加到 ViewComponent 并将它们传递给 ViewComponent 视图本身。

    <vc:some-component title="Title" 
    body="@Html.Raw("<div>this is a nice div, my name is @Model.Name</div>")">
    </vc:some-component>
    

    或类似的东西

     @await Component.InvokeAsync("SomeComponent", new { title="Title", body= Html.Raw($"<div>this is a nice div, my name is {Model.Name}</div>") })
    

    您的视图组件 IViewComponentResult 看起来像这样,以 ViewBag 为例

    public async Task<IViewComponentResult> InvokeAsync(string title, string body)
    {
        //...
        ViewBag.Content = body;
        ViewBag.Title = title;
        //...
        return View();
    }
    

    然后在相关的ViewComponent中查看

    <div>
        <p>@ViewBag.Title</p>
        @ViewBag.Content
    </div>
    

    创建一个更具体的 ViewModel 来传递也是一种选择

    【讨论】:

      【解决方案2】:

      是的,这是可能的,您必须采取一种解决方法,但这是可以实现的,this answer 有一个您正在寻找的示例。

      【讨论】:

      • 所以这实际上是一个重复的问题?
      • 不完全但非常相似。
      • 我尝试了该解决方案,但它不适合我。当我尝试传递 csHtml 时,出现此编译时错误:“无法将类型 'System.Func' 隐式转换为 'Microsoft.AspNetCore.Html.HtmlString'”。
      • 代码如下:@{Func children = @

        aaaa

        bbbb

        ccccc

        }
      • 我的错,我错过了添加分号。现在它正在呈现,但在页面上它看起来像这样“System.Func`2[System.Object,System.Object]”,它没有正确呈现实际的 HTML。
      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2020-01-26
      • 1970-01-01
      相关资源
      最近更新 更多