Search code examples
javascriptjqueryjsviews

Using jsViews/jsRender with a property retuned as dictionary entries


I was wondering why cannot seem to get this down correctly. I have a JSONResult in MVC returning a collection of "Job" objects. One of the properties of the "Job" objects is a Dictionary. I cannot seem to figure out how to add this to the "Job" entity template, so that I can display all values for the inner template. The current object design would be a job, and each job has a dictionary of job phases. The following code is what I am currently using:

Job.cs

  public string Id { get; set; }
    public string Name { get; set; }
    public string CustomerName { get; set; }
    public string Phase {get;set;}
    public string PhaseText { get; set; }
    public Dictionary<String,String> Codes { get; set; }

The client side script:

<script id="jobLevelTmpl" type="text/x-jsrender">
        <tr class="row-header">
            <td class="col-lg-1">{{:Id}}</td>
            <td class="col-lg-4">{{:Name}}</td>
            <td class="col-lg-1" title="Status code: '{{:Phase}}'">{{:PhaseText}}</td>
            <td class="col-lg-1"><a jobid="{{:Id}}">View Job Details</a></td>
            <td class="col-lg-1">
                <div class="dropdown">
                    <button class="btn btn-warning dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">
                        Phase
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
                        {{for Codes}}
                           <!-- This is where I do not know what to call or how to call the key or value of the dictionary items -->                            
                           <li role="presentation" class="dropdown-header">{{>code}}</li>
                        {{/for}}
                   </ul>              
               </div>
            </td>
            <td class="col-lg-1"><a href="javascript:function(){return false;}" jobid="{{:Id}}" class="btn btn-info expand-job">Update</a></td>
        </tr>
        <tr>
            <td class="col-lg-12 details-info" style="display:none;">
                <a href='#' onclick='parent.$.colorbox.close(); return false;' style="float:right;">Close</a>

            </td>
        </tr>      
    </script>

Solution

  • If the client side JSON for Codes corresponds to a plain JavaScript object with string values, then you can use {{props}} to iterate through the properties - for example:

    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
        {{props Codes}}
            <li role="presentation" class="dropdown-header">Key: {{>key}} Value: {{>prop}}</li>
        {{/props}}
    </ul> 
    

    See http://www.jsviews.com/#propstag