Search code examples
razorjsrender

how do I inject an object from my html into the jsRender template


In my cshtml I start off with some regular html/razor syntax which go in the form

@foreach (var product in Model.Basket.Items
{
 ……
  <div class="itemMessageContent></div>
}

where the div is the target of my template.

So how do I inject product into the template? or is it already available to me on the basis the div's in side my foreach?


Solution

  • Recommend add the template before the </body> tag:

    <script id="template" type="text/x-jsrender">
        {{:name}}
    </script>
    

    Data attribute way

    Most obvious and somewhat erroneous decision.

    Add to your project Newtonsoft.Json

    Install-Package Newtonsoft.Json
    

    Update code:

    @foreach (var product in Model.Basket.Items)
    {
      <div data-jsrender='@JsonConvert.SerializeObject(product)' class="itemMessageContent"></div>
    }
    

    The following html should turn out:

     <div data-jsrender='{name="Apple"}' class="itemMessageContent></div>
     <div data-jsrender='{name="Banana"}' class="itemMessageContent></div>
    

    Now you can render data:

    var template = $('#template');
    $('.itemMessageContent').each(function(){
        var element = $(this);
        var data = element.data('jsrender');
        element.html(template.render(data));
    })