Search code examples
c#jqueryasp.net-mvcfuelux

Send model to Jquery


I would like to create tree in my mvc view using Fuelux jquery plugin. To use this plugin I have to send data to plugin with next code:

$('#MyTree').tree({ dataSource: dataSource })

I don't have any idea how to send my model object in view as parameter to plugin. What structure data must have?


Solution

  • You need to conver you model to Json and use the converted object as a datasource:

    <script>
    $(dcoument).ready(function(){
    
    var datasource = @ViewBag.JsonModel;
    $('#MyTree').tree({ dataSource: dataSource });
    
    });
    </script>
    

    Now you need to populate ViewBag.JsonModel in the action:

    public ViewResult YourActionName()
    {
     // your logic on getting model
    ViewBag.JsonModel = //convert model to json using jsonserializer
    }
    

    Here is tree plugin example:

     // INITIALIZING TREE
    var treeDataSource = new TreeDataSource({
    data: [
    { name: 'Test Folder 1', type: 'folder', additionalParameters: { id: 'F1' } },
    { name: 'Test Folder 2', type: 'folder', additionalParameters: { id: 'F2' } },
    { name: 'Test Item 1', type: 'item', additionalParameters: { id: 'I1' } },
    { name: 'Test Item 2', type: 'item', additionalParameters: { id: 'I2' } }
    ],
    delay: 400
    });
    $('#MyTree').tree({dataSource: treeDataSource});