Search code examples
c#jqueryajaxasp.net-mvcmustache

Get data with AJAX call and templify them with Mustache


I'm trying to templify data from an AJAX call on the client side. The data is present in the data argument in the success function, but somehow it doesn't 'see' it. It's not displaying the data that should be placed in the template.

This is the controller:

[HttpPost]
public object SetFilters(dynamic param)
{
     var t = _servrep.GetAvailableServices(param.filters);
     return Enumerable.Select(t,(Func<dynamic, dynamic>) 
                   (x => new { x.Name, x.Comments }));
 } 

This is the success function of the AJAX call:

success: function (data) 
{
    //debugger;
    //var sdata = JSON.stringify(data);
    var template = $('#serviceTemplate').html();
    var html = Mustache.to_html(template, data);
    $('#servicePlaceholder').html(html);
},

When I uncomment the debugger statement in the success function, the data looks like this: [[object Object],[object Object],[object Object],[object Object]]

When I expand it, I do see the key value pairs Name and Comments with a value.

What am I missing?

[EDIT]

<script id="serviceTemplate" type="text/template">
    <li>
        <h4>{{Name}}</h4>
        <div>
            {{Comments}}

        </div>
    </li>
</script>

Solution

  • It looks like you have an array of objects. Maybe try indexing your data before passing it to Mustache.

     var html = Mustache.to_html(template, data[0]);
    

    Or you can try looping through each one. I'm not too familiar with the mustache syntax but it should look something like this

    //JS
    var html = Mustache.to_html(template, {data: data});
    
    //template
    
    {{#data}}
        <p>{{name}}</p>
        <p>{{comments}}</p>
    {{/data}}