locked
Handsontable Get Data MVC RRS feed

  • Question

  • User197255166 posted

    Hi,

    I am using https://handsontable.com . But how can I get data with MVC ? Can anyıne help me please.

    HTML

    <div id="hot"></div>

    MVC CS

     public JsonResult Tables()
            {
                using (PortfoliosContext port = new PortfoliosContext())
                {
                    var dil = port.TProjeCategory.AsQueryable().ToList();
                    ViewBag.Cat = dil;
    
                    return Json(dil);
                }
            }

    JS

    <script>
        (function ($) {
            if ($) {
                var hst = (function () {
                    var $container = $("#hot");
    
                    $container.handsontable({
                        startRows: 8,
                        startCols: 6,
                        rowHeaders: true,
                        colHeaders: true,
                        minSpareRows: 1,
                        contextMenu: true
                    });
    
                    hst = $container.data('handsontable');
    
                    var $dataLocker = $("#Tables").val();
    
                    if ($dataLocker.length > 0) {
                        var data = JSON.parse($dataLocker);
    
                        hst.loadData(data);
                    }
                    return hst;
                })();
    
          
            }
        })(jQuery);
    </script>

    Wednesday, April 3, 2019 5:05 PM

All replies

  • User1724605321 posted

    Hi Aliyilmaz,

    The basic idea is to use Jquery Ajax to call server side function and return json data :

    jQuery.ajax({
                url: '/Home/GetCar', //Controller to Get the 
                //JsonResult From -- Json(jsonData, JsonRequestBehavior.AllowGet);
                type: "GET",
                dataType: "json",
                contentType: 'application/json; 
                charset=utf-8', // dataType and contentType should be json
                async: true,
                processData: false,
                cache: false,
                success: function (data) {      // on Success send the Json data 
                					// to the table by using loaddata function""
                    //alert(data);
                    hot.loadData(data);
                    exampleConsole.innerHTML = 'Data loaded';
                },
                error: function (xhr) {
                    alert('error');
                }
            });

    Please take a look at this example for more details on how to implement "Handsontable" with MVC

    http://www.codeproject.com/Tips/1074230/Load-and-save-Handsontable-data-from-to-Controller

    Best Regards,

    Nan Yu

    Thursday, April 4, 2019 1:50 AM
  • User283528319 posted

    Don't know <g class="gr_ gr_8 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="8" data-gr-id="8">handsontable</g> but if you need to get data from an MVC controller just follow this technique.

    <g class="gr_ gr_14 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="14" data-gr-id="14">Lets</g> say you use Entity <g class="gr_ gr_10 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" id="10" data-gr-id="10">frame work</g> and you simply need Turkiye'nin Illeri list. Make a controller like this.

        public IList<string> TumIllerListesi()
            {
                return _context.Set<Iller>().Select(u => u.Il).ToList();
            }
    

    now use jquery $.get method to get that list as data

     $.get('/MyController/TumIllerListesi', function (data) {
    
    //do what ever you want with that list in here
    })

    If you need data as <g class="gr_ gr_11 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="11" data-gr-id="11">json</g> (probably you will need it for handsome one :) you need to convert It to <g class="gr_ gr_12 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="12" data-gr-id="12">json</g> like below

           public IActionResult BenimAction(int EvrakId)
            {
                Evraklar EvrakBilgileri = _context.Set<Evraklar>().Find(EvrakId);
    
                return Json(EvrakBilgileri);
            }

    and this time you need to use getJson instead of simple get

      $.getJSON("/MyController/MyAction" {EvrakId:document.getElementybyId('MyEvrakId').value}, function (data) {
    //bla bla bla
    })

    Saturday, April 6, 2019 11:08 AM
  • User197255166 posted

    I try this but it doesnt work,

    I get error below code. "Uncaught TypeError: Cannot read property 'addEventListener' of undefined"

    Handsontable.Dom.addEvent(load, 'click', function () {

        <script type="text/javascript">
    
        // Variables declaration & to make our life easier we set our HTML tags to variables too
        var
            $$ = function(id) {return document.getElementById(id);},
            container = $$('example1'),
            exampleConsole = $$('example1console'),
            autosave = $$('autosave'),
            save = $$('save'),
            load = $$('load'),
            autosaveNotification,
            hot;
    
        hot = new Handsontable(container, {
            startRows: 8,
            startCols: 6,
            rowHeaders: true,
            colHeaders: true,
            // This is for the AutoSave func
            afterChange: function(change, source) {
                if (source === 'loadData') {
                    return; //don't save this change
                }
                if (!autosave.checked) {
                    return;
                }
                clearTimeout(autosaveNotification);
                jQuery.ajax({
                    url: '@Url.Action("AddCar")',
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify(hot.getData()),
                    async: true,
                    processData: false,
                    cache: false,
                    success: function (data) {
                        exampleConsole.innerHTML = 'Changes will be autosaved';
                        autosaveNotification = setTimeout(function () {
                            exampleConsole.innerHTML = 'Autosaved (' + change.length +
                            ' ' + 'cell' +
                            (change.length > 1 ? 's' : '') + ')';
                        }, 1000);
                        //alert(data);
                    },
                    error: function(xhr) {
                        exampleConsole.innerHTML = 'Autosave: No Response from Controller';
                        //alert('error');
                    }
                });
            }
          // End of AutoSave func
        });
    
        // GET method gets data from the Controller
        Handsontable.Dom.addEvent(load, 'click', function () {
            jQuery.ajax({
                url: '/Home/GetData', //Controller to Get the
                			//JsonResult From -- Json(jsonData, JsonRequestBehavior.AllowGet);
                type: "GET",
                dataType: "json",
                contentType: 'application/json',          
                async: true,
                processData: false,
                cache: false,
                success: function (data) {      // on Success send the Json data
                					// to the table by using loaddata function""
                    //alert(data);
                    hot.loadData(data);
                    exampleConsole.innerHTML = 'Data loaded';
                },
                error: function (xhr) {
                    alert('error');
                }
            });
    
            // POST method gets data to the Controller
            Handsontable.Dom.addEvent(save, 'click', function () {
                jQuery.ajax({
                    url: '/Home/AddCar',
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify(hot.getSourceData()),
                    async: true,
                    processData: false,
                    cache: false,
                    success: function (data) {
                        exampleConsole.innerHTML = 'Data saved';
                        //alert(data);
                    },
                    error: function (xhr) {
                        exampleConsole.innerHTML = 'Save error';
                        //alert('error');
                    }
                });
            });
    
            Handsontable.Dom.addEvent(autosave, 'click', function() {
                if (autosave.checked) {
                    exampleConsole.innerHTML = 'Changes will be autosaved';
                }
                else {
                    exampleConsole.innerHTML = 'Changes will not be autosaved';
                }
            });
        });
    
        </script>

    Sunday, April 7, 2019 10:55 AM
  • User1724605321 posted

    Hi Aliyilmaz ,

    Try to change Dom to dom ,seems Handsontable make the changes from version v1.11.0 :

    https://forum.handsontable.com/t/cannot-read-property-addevent-of-undefined/1372 

    Best Regards,

    Nan Yu

    Monday, April 8, 2019 1:57 AM