【问题标题】:How do I pass a model to a razor pages custom helper如何将模型传递给剃须刀页面自定义助手
【发布时间】:2019-06-05 13:35:59
【问题描述】:

我想将模型传递给自定义剃须刀助手以执行重复的剃须刀生成任务。我想要生成的代码如下所示:

@foreach (Place P in Model.Places)
{
<div class="col-md-4 clsBorder">
    @if (P.prop1 != null && P.prop1  != "")
    {<div class="row ">
        <div class="col-6">
            @Html.DisplayNameFor(model => P.prop1 )
        </div>
        <div class="col-6">
            @Html.DisplayFor(model => P.prop1 )
        </div>
    </div>}
    @if (P.prop2 != null && P.prop2  != "")
    {<div class="row">
        <div class="col-6">
            @Html.DisplayNameFor(model => P.prop2)
        </div><div class="col-6">

            @Html.DisplayFor(model => P.prop2)
        </div>
    </div>}
</div>
}

显然,Model.Places 中可能有超过 2 个 Place 对象,并且每个 Place 对象中可能有更多的 prop1 和 prop2。

那么如何传递 Places 对象(可能是 List&lt;customClass&gt;),并为每个属性生成代码?

【问题讨论】:

  • 您将如何确定列表? prop1prop2 你将如何根据这些生成列表?
  • 您是否有理由希望拥有自定义助手而不是局部视图?
  • @Justcode - 如果没有其他机制,则使用反射
  • @DarjanBogdan - 看起来更优雅

标签: html-helper razor-pages


【解决方案1】:

怎么样,你命名你的辅助方法并在参数模型周围加上括号。

@Util.MyUtilMethod(Model.Places)

假设您的辅助方法调用了将模板呈现为字符串的服务

public static class Util
{
    //...
    public async string MyUtilMethod(List<customClass> places)
    {
      return await this._viewRenderService.RenderToStringAsync(
       "blahContext/blahAction", 
        new blahContext.blahModel { Places = places});
    }
    //...
}

Render a Razor Page to string 的示例。

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 2015-08-01
    • 2020-03-27
    • 2018-05-19
    • 2020-06-06
    • 1970-01-01
    • 2021-06-29
    • 2020-02-20
    • 2022-10-16
    相关资源
    最近更新 更多