We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Grid with CRUD Server Side Actions don't refresh


Hi.

I need update the grid at the finish of the actionComplete event, my services take of the controller service the new list of data, but grid doesn't show or refresh.

I have this code in my view:

    var objConfig = {};
    var urlBase = "/SyncFusion/CadenaRadio/";
    var registros = [];
    var dataManager;
    
    $(document).ready(function (e) {
        var ColumnsCadena = [
            { field: "CadenaId", headerText: "ID", isPrimaryKey: true, visible:false },
            { field: "CadenaClave", headerText: "Clave", width: '10%', allowEditing: false },
            { field: "CadenaNombre", headerText: "Nombre", width: '65%', validationRules: { required: true, maxLength: 50 } },
            { field: "CadenaActivo", headerText: "Activo", width: '10%', textAlign: ej.TextAlign.Center, editType: ej.Grid.EditingType.Boolean },
            {
                headerText: " ", commands: [
                  { type: ej.Grid.UnboundType.Edit, buttonOptions: { text: "Editar" } },
                  { type: ej.Grid.UnboundType.Delete, buttonOptions: { text: "Eliminar" } }
                ], isUnbound: true, width: '15%'
            }
        ];

        objConfig = {
            nombreGrid: "#divGrid",
            urlFiltrar: urlBase + "FiltrarRegistros",
            dataManagerGrid: createDataManager(),
            columnasGrid: ColumnsCadena
        };
        
        $(objConfig.nombreGrid).ejGrid({
            dataSource: objConfig.dataManagerGrid,
            width: '100%',
            allowPaging: true,
            allowSorting: true,
            allowReordering: true,
            allowTextWrap: true,
            allowFiltering: true,
            showStackedHeader: true,
            filterSettings: { filterType: "menu" },
            pageSettings: { pageSize: 50 },
            selectionType: "multiple",
            selectionSettings: { enableToggle: true },
            allowKeyboardNavigation: true,
            locale: "es-ES",            
            editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: ej.Grid.EditMode.Dialog },
            actionBegin: actionBeginEvent,
            actionComplete: actionCompleteEvent,
            actionFailure: actionFailureEvent,
            columns: objConfig.columnasGrid
        });

        crearBotones();

        function actionBeginEvent(args) {
            if (args.requestType === "add") {
                var urlObtenerClave = resuelveURL(urlBase + "TraeClaveNueva")
                $.ajaxSetup({ async: false });
                $.getJSON(urlObtenerClave, null, function (json) {
                    args.data.CadenaClave = json;
                    args.data.CadenaActivo = true;
                }, "json");
            }
        }

        function actionCompleteEvent(args) {
            debugger;
            if (args.requestType === "add") {
                dataManager = ej.DataManager({
                    json: refrescaRegistros()
                });

                $(objConfig.nombreGrid).ejGrid("refreshContent", true);
            }

            if (args.requestType === "delete") {
                dataManager = ej.DataManager({
                    json: refrescaRegistros()
                });

                $(objConfig.nombreGrid).ejGrid("render");

                $(objConfig.nombreGrid).ejGrid("refreshContent", true);
            }

            if (args.requestType === "save") {
                var gridObj = $(objConfig.nombreGrid).ejGrid("instance");
                gridObj.dataSource = createDataManager();
                gridObj.refreshContent();
                gridObj.render();
            }
        }

        function actionFailureEvent(args) {
            debugger;
        }
    });

    obtenerRegistros = function () {
        $.ajaxSetup({ async: false });
        $.getJSON(resuelveURL(urlBase + "TraeRegistros"), null, function (json) {
            registros = json;
        }, "json");
    };

    refrescaRegistros = function () {
        obtenerRegistros();

        return registros;
    };

    createDataManager = function () {
        dataManager = ej.DataManager({
            json: refrescaRegistros(),
            adaptor: "remoteSaveAdaptor",
            updateUrl: resuelveURL(urlBase + "EditarRegistro"),
            insertUrl: resuelveURL(urlBase + "AgregarRegistro"),
            removeUrl: resuelveURL(urlBase + "EliminarRegistro"),
            offline: false
        });

        return dataManager;
    };

    crearBotones = function () {
        $("#divToolbar").ejToolbar();
        $("#btnQuitarBusq").ejButton({
            size: "Medium",
            showRoundedCorner: true,
            contentType: "textandimage",
            prefixIcon: "btnQuitarFiltros"
        });
        $("#btnBuscar").ejButton({
            showRoundedCorner: true,
            contentType: "textandimage",
            prefixIcon: "btnBuscar"
        });
        $("#btnAgregar").ejButton({
            showRoundedCorner: true,
            contentType: "textandimage",
            prefixIcon: "btnAgregar",
            click: function (args) {
                var gridObj = $(objConfig.nombreGrid).data("ejGrid");
                gridObj.addRecord();
            }
        });
        $("#btnExportarExcel").ejButton({
            showRoundedCorner: true,
            contentType: "textandimage",
            prefixIcon: "btnExportarExcel"
        });
        $("#btnExportarPdf").ejButton({
            showRoundedCorner: true,
            contentType: "textandimage",
            prefixIcon: "btnExportarPdf"
        });
        $("#btnImprimir").ejButton({
            showRoundedCorner: true,
            contentType: "textandimage",
            prefixIcon: "btnImprimir",
            click: function (args) {
                var obj = $(objConfig.nombreGrid).ejGrid("instance");
                obj.print();
            }
        });
    };


And my controller looks like that:

public JsonResult TraeRegistros()
        {
            #region Trae Registros para Grid
            try
            {
                List<CadenaRadioVw> listaRegistros = new List<CadenaRadioVw>();
                listaRegistros = _Bl.TraeListaRegistros(null);

                return Json(listaRegistros, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("TraeRegistros", ex.Message);
                return Json("Error", JsonRequestBehavior.AllowGet);
            }
            #endregion
        }

5 Replies

PK Prasanna Kumar Viswanathan Syncfusion Team June 3, 2015 11:19 AM UTC

Hi Christhian,

Thanks for using Syncfusion Products.

We have analyzed your code snippet and could please confirm the following details with us?

1. In actionComplete event, in which action you need to update the source for the grid?

2. In actionComplete event you have bound the JSON data using ej.DataManager and assigned in a dataManager variable. But the datasource has been bound for the grid using CreateDataManager function when the requestType is save. So, what is the use of DataManager variable?

3. Could you please tell us whether you are updating Grid datasource after adding new data or after adding new data you refresh the grid content with new datasource?

4. In the code snippet, you have used refreshContent and render methods. The refreshContent is used to refresh the grid contents in the grid. Without binding the dataSource for the grid, you have used refreshContent method. The render method is used to render the initial grid. So, could you able to provide more information?

5. Share your Essential Studio version details

Please get back to us with further details, we will be happy to assist you,

Regards,
Prasanna Kumar N.S.V


CV Christhian Villa replied to Prasanna Kumar Viswanathan June 3, 2015 06:22 PM UTC

Hi Christhian,

Thanks for using Syncfusion Products.

We have analyzed your code snippet and could please confirm the following details with us?

1. In actionComplete event, in which action you need to update the source for the grid?

2. In actionComplete event you have bound the JSON data using ej.DataManager and assigned in a dataManager variable. But the datasource has been bound for the grid using CreateDataManager function when the requestType is save. So, what is the use of DataManager variable?

3. Could you please tell us whether you are updating Grid datasource after adding new data or after adding new data you refresh the grid content with new datasource?

4. In the code snippet, you have used refreshContent and render methods. The refreshContent is used to refresh the grid contents in the grid. Without binding the dataSource for the grid, you have used refreshContent method. The render method is used to render the initial grid. So, could you able to provide more information?

5. Share your Essential Studio version details

Please get back to us with further details, we will be happy to assist you,

Regards,
Prasanna Kumar N.S.V

Hi Prasanna.

Thanks for you response, The version i use is 4.0.30319,  but i think i found the solution, for the further questions on this subject, here is my solution:

In my contoller:

public JsonResult TraeRegistros(int skip, int take)
        {
            #region Trae Registros para Grid
            try
            {
                List<CadenaRadioVw> listaRegistros = new List<CadenaRadioVw>();
                listaRegistros = _Bl.TraeListaRegistros(null);

                return Json(new { result = listaRegistros.Skip(skip).Take(take).ToList(), count = listaRegistros.Count() }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("TraeRegistros", ex.Message);
                return Json("Error", JsonRequestBehavior.AllowGet);
            }
            #endregion
        }
In my script:
function actionCompleteEvent(args) {
            if (args.requestType === "add" || args.requestType === "delete" || args.requestType === "save") {
                var gridObj = $(objConfig.nombreGrid).ejGrid("instance");
                gridObj.refreshContent();
            }
        }


createDataManager = function () {
        dataManager = ej.DataManager({
            adaptor: "UrlAdaptor",
            url: resuelveURL(urlBase + "TraeRegistros"),
            updateUrl: resuelveURL(urlBase + "EditarRegistro"),
            insertUrl: resuelveURL(urlBase + "AgregarRegistro"),
            removeUrl: resuelveURL(urlBase + "EliminarRegistro"),
        });

        return dataManager;
    };



Now i have another question, I validations in my Business layer , usually with other controls I return a JSON object with the result and I checked if there was an error or not , is there any way to access this object, or some form of take the response from the controller

Thanks in advance!!

Regards


PK Prasanna Kumar Viswanathan Syncfusion Team June 4, 2015 01:36 PM UTC

Hi Christhian,
Thanks for the Update,

We are happy that you have found the solution.

Your other requirement has been achieved by the actionFailure Event in ejGrid. In this event, we can able to get error details in the arguments. Using that we can open alert box to describe what type of exception is thrown. Please find the below code snippet:

$(function () {

        $("#Grid").ejGrid({

            dataSource: ej.DataManager({ url : "/Grid/DataSource/", updateUrl: "/Grid/Update", insertUrl: "/Grid/Insert", removeUrl: "/Grid/Delete", adaptor: "UrlAdaptor" }),

            actionComplete: "complete",

            allowPaging : true,

            allowSorting: true,

            ---------------------------------------------------------

           actionBegin: "actionbegin",

            actionFailure: "FailureEvent",

            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel] },

            columns: [

                    { field: "OrderID", isPrimaryKey: true, headerText: "Order ID", textAlign: ej.TextAlign.Right, validationRules: { required: true, number: true }, width: 90 },

                    { field: "CustomerID", headerText: 'Customer ID', validationRules: { required: true, minlength: 3 }, width: 90 },

                    { field: "EmployeeID", headerText: 'Employee ID',  textAlign: ej.TextAlign.Right, width: 80, validationRules: { number: true } },

                    { field: "Freight", headerText: 'Freight', textAlign: ej.TextAlign.Right, editType: ej.Grid.EditingType.Numeric, editParams: { decimalPlaces: 2 }, validationRules: { range: [0, 1000] }, width: 80, format: "{0:C}" },

                    { field: "ShipName", headerText: 'Ship Name', width: 150 },

                    { field: "ShipCountry", headerText: 'Ship Country', width: 90 }

            ]

        });

    });


    function FailureEvent(args)

    {

        alert($($(args.error.responseText).find('b')[0]).text() + ":" + $(args.error.responseText).find('i').text());

    }
</script>

---------------------------------------------------------------------------------------------

  public JsonResult DataSource(Syncfusion.JavaScript.DataManager dm)

        {

            try

            {

                var DataSource = OrderRepository.GetAllRecords();

                throw new Exception();

                DataResult result = new DataResult();

                result.result = DataSource.Skip(dm.Skip).Take(dm.Take).ToList();

                result.count = DataSource.Count();

                return Json(result, JsonRequestBehavior.AllowGet);

            }

            catch (Exception ex)

            {

                return Json(ex, JsonRequestBehavior.AllowGet);

            }
        }


For your convenience we have created a sample and same can be downloaded from the below link

Sample Link : http://www.syncfusion.com/downloads/support/forum/119297/ze/Sample1271935333

In your query, you have asked regarding validation, could you please let us know whether you are expecting server side validation?

If we misunderstood your query, Please get back to us, we will be happy to assist you,

Regards,
Prasanna Kumar N.S.V


CV Christhian Villa June 4, 2015 05:54 PM UTC

Hi Prasanna.

Thanks for your time, the regarding validations on Busnines Layer is very easy, only validate if the name exist, and my BL method return an object with the response, the controller checks for errors in the object:

Estructura<CadenaRadioVw> objEstructura = new Estructura<CadenaRadioVw>();
objEstructura.Entidad = value;
objEstructura = _Bl.EditarRegistro(objEstructura);
if (objEstructura.Error)
return ErrorJsonWithOutException(objEstructura.Mensaje, (int)Enumeradores.TiposDeErrores.Validacion);
else
return ConfirmViaJson(objEstructura.Entidad.CadenaId, string.Format(Textos.StrFormatConfirmarAccion, "actualizó", nombreObjeto));


public JsonResult ErrorJsonWithOutException(string mensaje, int tipoError)
        {
            ErroresJson objError = new ErroresJson();
            objError.Error = true;
            objError.tipoError = tipoError;
            objError.Mensaje = mensaje;

            return Json(objError, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ConfirmViaJson(int? id)
        {
            ErroresJson objError = new ErroresJson();
            objError.Error = false;
            objError.Mensaje = "Se realizo exitosamente el cambio solicitado.";
            if (id != null)
                objError.Id = id.Value;

            return Json(objError, JsonRequestBehavior.AllowGet);
        }

"ErrorJsonWithOutException" and "ConfirViaJson" both methods only create an object with the information to make the return Json, but not is a Exception.

I probe with the ActionFailure and not fire and  ActionComplete event check in the args but it was useless, there is another way besides that you show me?

Thanks in advance!!..

Regards




PK Prasanna Kumar Viswanathan Syncfusion Team June 5, 2015 11:23 AM UTC

Hi Christhian,

Sorry for the inconvenience caused.

Your requirement has been achieved by using actionbegin event of ejGrid. This event triggers for every grid action. While saving the record, we can able to get the data in arguments and send the data using ajaxPost to the controller.


In controller we have checked the condition with modelstate.IsValid. If it is false, we will get the error message by using for each loop and we can able to get the data in the arguments of the success function. So, we will be able to get the error details in the arguments of the success function and display in the dialog box.

Please find the below code snippet :

<div id="Grid"></div>

<script type="text/javascript">

    var genData = [];

    var dataManager;

    $(function () {

        $("#Grid").ejGrid({        

            actionComplete: "complete",

            allowPaging : true,

            allowSorting: true,

            allowReordering: true,

            allowTextWrap: true,

            allowFiltering: true,

            showStackedHeader: true,

            filterSettings: { filterType: "menu" },

            pageSettings: { pageSize: 10 },

            selectionType: "multiple",

            selectionSettings: { enableToggle: true },

            allowKeyboardNavigation: true,

            locale: "es-ES",

            editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true },

            actionBegin: "actionbegin",

            actionFailure: "FailureEvent",

            toolbarSettings: { showToolbar: true, toolbarItems: [ej.Grid.ToolBarItems.Add, ej.Grid.ToolBarItems.Edit, ej.Grid.ToolBarItems.Delete, ej.Grid.ToolBarItems.Update, ej.Grid.ToolBarItems.Cancel] },

            columns: [

                    { field: "OrderID", isPrimaryKey: true, headerText: "Order ID", textAlign: ej.TextAlign.Right, validationRules: { required: true, number: true }, width: 90 },

                    { field: "CustomerID", headerText: 'Customer ID', validationRules: { required: true, minlength: 3 }, width: 90 },

                    { field: "EmployeeID", headerText: 'Employee ID',  textAlign: ej.TextAlign.Right, width: 80, validationRules: { number: true } },

                    { field: "Freight", headerText: 'Freight', textAlign: ej.TextAlign.Right, editType: ej.Grid.EditingType.Numeric, editParams: { decimalPlaces: 2 }, validationRules: { range: [0, 1000] }, width: 80, format: "{0:C}" },

                    { field: "ShipName", headerText: 'Ship Name', width: 150 },

                    { field: "ShipCountry", headerText: 'Ship Country', width: 90 }

            ]

        });

    });


   @(Html.EJ().Dialog("ErrorList").ShowOnInit(false).Title("Error List"))

<script type="text/javascript">

    var flag = true;

    function actionbegin(args) {

        if (args.requestType == "save" && flag) {

            flag = true;

            var record = args.data;

            args.cancel = true;

            $.ajax({

                url: "/Home/Validate",

                type: "POST",

                data: record,

                success: function (data) {

                    var errorlist = JSON.parse(data);

                    var i;

                    if (errorlist.length) {

                        var str = "";

                        $.each(errorlist, function (index, error) {

                            str += "<tr><td>" + error + "</td></tr>";

                        });

                        $("#ErrorList").html("<table>" + str + "</table>");

                        $("#ErrorList").ejDialog("open");

                    }

                    else {

                        var gridobj = $("#Grid").data("ejGrid");

                        gridobj.endEdit();

                        flag = false;

                    }

                },

                error: function (e) {

                    args.cancel = true;

                }

            });

        }

        if (flag == false)

            flag = true;

    }
</script>
------------------------------------------------------------------------------

public ActionResult Validate(EditableOrder order)

        {

            if (!ModelState.IsValid)

            {

                List<string> errorlist = new List<string>();

                foreach (ModelState modelState in ModelState.Values)

                {

                    foreach (ModelError error in modelState.Errors)

                    {

                        errorlist.Add(error.ErrorMessage);

                    }

                }

                return Content(new JavaScriptSerializer().Serialize(errorlist));

            }

            return Content("true");
        }


For your convenience we have created a sample and same can be downloaded from the below link:

Sample Link : http://www.syncfusion.com/downloads/support/forum/119297/ze/EJGrid129714848

Please let us know if you have any further assistance,

Regards,
Prasanna Kumar N.S.V

Loader.
Live Chat Icon For mobile
Up arrow icon