Wednesday, April 20, 2016

Mustache JS Ajax call

Earlier we saw how we can use MustachJs to display the hardcoded data in the browser.
Now lets call our MVC controller thru ajax  and get the data and then display it on browser


For this additional we got to add Jquery CDN for ajax calls


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>


Below is the script to make an ajax "Get" call to the controller and display the data



<script>

        var template,  html;

     

        $.getJSON('http://localhost:52456/api/RiskDetailApi', function (data) {

            debugger

            template = "<h2>RiskDecription: {{RiskDecription}} </h2>";

           

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

            document.write(html);

        });

     

      

      

    </script>




$.getJSON converts the data to Json format
Run the solution and BOOOM!!! you see the dynamic data on the browser


Mustache Js -Get Started

I came across this super cool “Logic-less” Templating  js library called MustacheJS .


Note :By “Logic-less” I mean to say they do not use conditional constructs like if else or looping constructs like for ,foreach and while .




How to Use :


Download the CDN from here https://cdnjs.com/libraries/mustache.js/


or copy this -> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.min.js"></script>




Now you got to set up your data which you want to display. Typically in Json Format


add that in ur script tag


data = {
name: "Supreet P Hadagali",

Designation:"Module Lead"





};


create a template .
Its a just a string you want to display on your screen
when you want to reference the data and show it on browser , its simple as similar to angular expression. Use double mustache -->   {{  }} 


 Render the HTML


its very simple . we have an inbuilt function called




Mustache.to_html()


overall here is the script code


<script>


var template, data, html;






data = {
name: "Supreet P Hadagali",

Designation:"Module Lead"





};
template = "<h2>Name: {{name}} <br/> Designation : {{Designation}}</h2>";






html = Mustache.to_html(template, data);


document.write(html);
</script>



Note : to_html() is deprecated . you can use render()
run your solution and see the data being displayed