4

I want to pass a model to a custom razor helper to perform a repetitive Razor generation task. The code that I want to be generated will look like:

@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>
}

Obviously there may be more then 2 Place objects in Model.Places, and many more then prop1 and prop2 in each Place object.

So how do I pass the Places object, which may be a List<customClass>, and have the code generated for each property?

GilShalit
  • 6,175
  • 9
  • 47
  • 68

1 Answers1

0

How about, you name your helper method and put parentheses around the parameter model.

@Util.MyUtilMethod(Model.Places)

assuming your helper method calls a service that renders the template to string

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

an example of how to Render a Razor Page to string.

Margus
  • 19,694
  • 14
  • 55
  • 103