Search code examples
javascriptjqueryasp.net-mvcasp.net-corejsgrid

jsGrid Filtering issue calling data from .net controller


Successfully performing CRUD operations with jsGrid but unable able to get the filter working

I've searched everywhere (SO, YouTube, js-grid.com). Turning to the SO community for help after being stuck with this problem all day

View

@model MyNamespace.Models.ViewModels.VehicleViewModel
<h1>Vehicles</h1>
<div id="jsGrid"></div>

    <script>
    var lastPrevItem;

    $(function () {
        var result = $.Deferred();

            $("#jsGrid").jsGrid({
                height: "400px",
                width: "100%",
                inserting: true,
                editing: true,
                sorting: true,
                paging: true,
                autoload: true,
                loadMessage: "Please, wait...",
                pageSize: 10,
                pageButtonCount: 5,
                readonly: false,
                filtering: true,
                deleteConfirm: "Do you really want to delete?",

                controller: {
                    loadData: function (filter) {
                        var d = $.Deferred();
                        $.ajax({
                            type: "GET",
                            url: "/Vehicles/GridJsonGet",
                            data: {
                                data: filter
                            },
                            dataType: "json",
                            success: function (filter) {
                                filter ? console.log("success", filter) : alert("Could not load vehicles");
                            }

                        }).done(function (response) {
                                d.resolve(response);
                            });
                        return d.promise();
                    },

                    insertItem: function (item) {
                        var ajaxDeferredInsert = $.ajax({
                            type: "POST",
                            url: "/Vehicles/GridJsonPost",
                            data: item,
                            dataType: "json",
                            success: function (item) {
                                item ? console.log("Add Vehicle success") : alert("Vehicle could not be added");
                            }
                        });
                        ajaxDeferredInsert.done(function (insertItem) {
                            console.log("inserted item", insertItem);
                            result.resolve(insertItem);
                        }).fail(function () {
                            result.resolve(lastPrevItem);
                        });

                        return result.promise();
                    },

                    updateItem: function (item) {

                        var ajaxDeferredUpdate = $.ajax({
                            type: "PUT",
                            url: "/Vehicles/GridJsonPut/" + item.VehicleId,
                            data: item,
                            dataType: "json",
                            success: function (item) {
                                item ? console.log("Update success", item) : alert("Vehicle could not be updated");
                            }
                        });
                        ajaxDeferredUpdate.done(function (updatedItem) {
                            result.resolve(updatedItem);
                        }).fail(function () {
                            result.resolve(lastPrevItem);
                        });

                        return result.promise();
                    },

                    deleteItem: function (item) {
                        return $.ajax({
                            type: "DELETE",
                            url: "/Vehicles/GridJsonDelete/" + item.VehicleId,
                            data: item,
                            dataType: "json",
                            success: function (item) {
                                if (item) {
                                    console.log("Delete success");
                                }
                                else {
                                    alert("Vehicle could not be deleted");
                                    location.reload();
                                }
                            },
                        });
                    },
                },

                fields: [
                    {
                        name: "VIN",
                        title: "VIN",
                        type: "text",
                        width: 20
                    },
                    {
                        name: "Make",
                        title: "Make",
                        @*items: @Html.Raw(Model.VehicleMakesJson),*@
                        valueField: "Id",
                        textField: "Name",
                        type: "text",
                        width: 75,
                        filtering: true
                    },
                    {
                        name: "VehicleModel",
                        title: "Model",
                        items: @Html.Raw(Model.VehicleModelsJson),
                        valueField: "Id",
                        textField: "Name",
                        type: "select",
                        width: 75,
                        filtering: true
                    },
                    {
                        name: "InitialOdometer",
                        title: "Initial Odometer",
                        type: "number",
                        width: 40
                    },
                    {
                        name: "IsActive",
                        title: "Active",
                        width: 20,
                        type: "checkbox",
                        insertTemplate: function () {
                            var $result = jsGrid.fields.checkbox.prototype.insertTemplate.call(this);
                            $result.prop("checked", true);
                            return $result;
                        }
                    },
                    {
                        title: "View",
                        width: 20,
                        itemTemplate: function (value, item) {
                            var $customLink = $("<i>").attr({ class: "jsgrid-custom-button fas fa-external-link-alt" })
                                .click(function (e) {
                                    location = item.Link + item.VehicleId;
                                    e.stopPropagation();
                                });
                            return $("<div>").append($customLink);
                        },
                    },
                    {
                        type: 'control',
                        deleteButton: false,
                        width: 20
                    },
                ]
            });
    });
</script>

Controller

    public ActionResult Index()
    {
        VehicleViewModel model = new VehicleViewModel();
        model.Vehicles = service.GetVehicles();

        model.VehicleMakes.Add(new VehicleTypes
        {
            Id = 0,
            Name = ""
        });

        foreach (var item in model.Vehicles)
        {
            model.VehicleMakes.Add(new VehicleTypes
            {
                Id = item.VehicleId,
                Name = item.Make
            });
        }
        model.VehicleModels.Add(new VehicleTypes
        {
            Id = 0,
            Name = ""
        });

        foreach (var item in model.Vehicles)
        {
            model.VehicleModels.Add(new VehicleTypes
            {
                Id = item.VehicleId,
                Name = item.VehicleModel
            });
        }

        model.VehicleMakesJson = JsonConvert.SerializeObject(model.VehicleMakes);
        model.VehicleModelsJson = JsonConvert.SerializeObject(model.VehicleModels);

        return View(model);
    }

    [HttpGet]
    public string GridJsonGet(string filter)
    {            
        VehicleViewModel model = new VehicleViewModel();
        model.Vehicles = service.GetVehicles();
        json = JsonConvert.SerializeObject(model.Vehicles);
        return json;
    }

For some reason I can't seem to get one without the other either a select list or data populated in the grid.

On the field named 'Make' I have commented out the items array & set type as text, this gives me results in the grid but then I dont get a select list of makes.

On the field named 'VehicleModel' I am populating items from the viewmodel which gives me a select list but no data in the grid.

Not sure what I need to do differently?


Solution

  • The answer was so simple, I just had the wrong parameter name in my MVC controller method (smh)

    updated load data call (view)

    loadData: function (filter) {
      var d = $.Deferred();
      var filterData = JSON.stringify(filter);
      $.ajax({
          type: "GET",
          url: "/Vehicles/GridJsonGet",
          data: {
             data: filterData
          },
           dataType: "json"
       }).done(function (response) {
           d.resolve(response);
           });
           return d.promise();
       },
    
    
    
    
    updated controller method 
    
    public string GridJsonGet(string data)
        {            
            VehicleViewModel model = new VehicleViewModel();
    
            var gridData = JsonConvert.DeserializeObject<Vehicle>(data);
    
            if (!String.IsNullOrEmpty(gridData.Make))
            {
                model.Vehicles = service.GetVehiclesByFilter(gridData.Make);
    
            }
            if (!string.IsNullOrEmpty(gridData.VehicleModel))
            {
                model.Vehicles = service.GetVehiclesByFilter(gridData.VehicleModel);
    
            }
            else
            {
                model.Vehicles = service.GetVehicles();
            }
            json = JsonConvert.SerializeObject(model.Vehicles);
            return json;
        }