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

Set grid values in cells with editors

Good afternoon,

I'm having trouble trying to set values in cells of a grid which cells have editors of Datepickers and Dropdowns, I can do this without a problem but when I tried to asign values like I do for normal cells of the grid the method of the controller got null for the columns of datepickers and dropdowns

The columns for dropdowns are "Gender" and "Parentezco". And the columns for the datepickers are "FechaNacimiento" and "FechaAntiguedad"

The step 1 should be writing a value in the column "NumCertificado" and that triggers an event in the controller side, that returns values for the columns mentioned above. And I can read these values in the CRUD in the controller if the cells dont have the editors, but i got null with the editors.

Can you please help me with this problem?

In advance, thanks!

////////////////////////////////////////MY GRID IN THE VIEW////////////////////////////////////////
    <ejs-grid id="DetalleFormatoAltaGmmVidaApGrid" dataBound="dataBound" locale="es-MX" query="new ej.data.Query().addParams('FormatoID', '@Model.FormatoID')" toolbar="@(new List<string>() { "Cancel", "Update", "Add", "Delete" })">
        <e-data-manager id="dataManager" adaptor="UrlAdaptor" url="/Sistema/Formatos/DetalleFormatoAltaGmmVidaApGrid_Read/" crudUrl="/Sistema/Formatos/DetalleFormatoAltaGmmVidaApGrid_CRUD" requestType="Post"></e-data-manager>
        <e-grid-editSettings allowDeleting="true" allowEditing="true" allowAdding="true" mode="Normal" showDeleteConfirmDialog="true"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="DetalleID" isPrimaryKey="true" isIdentity="true" visible="false"></e-grid-column>
            <e-grid-column field="FormatoID" defaultValue="@Model.FormatoID" visible="false"></e-grid-column>
            <e-grid-column field="Seccion" headerText="Seccion" width="100" minWidth="100"></e-grid-column>
            <e-grid-column field="NumCertificado" headerText="No. Certificado"  width="140" minWidth="140" foreignKeyValue='ProductName' dataSource="@ViewBag.ForeignData" edit="@(new { create = "create", read = "read", destroy = "destroy", write = "write" })" width="180"></e-grid-column>
            <e-grid-column field="NombreAsegurado" headerText="Nombre del asegurado"  width="260" minWidth="260" visible="true"></e-grid-column>
            <e-grid-column field="TipoMovimiento" headerText="Tipo de movimiento"  width="190" minWidth="190" visible="true"></e-grid-column>

            <e-grid-column field="Parentezco" headerText="Parentezco"  width="140" minWidth="140" foreignKeyField="TipoParentezco" foreignKeyValue="Descripcion" dataSource="@ViewBag.TiposParentezco"></e-grid-column>
            e-grid-column field="Gender" headerText="Gender"  width="146" minWidth="146" foreignKeyField="TipoGender" foreignKeyValue="Descripcion" dataSource="@ViewBag.TiposGender"></e-grid-column>

            <e-grid-column field="FechaNacimiento" headerText="Fecha Nacimiento" width="160" minWidth="160" customFormat="@(new { type = "date", format = "dd/MM/yyyy" })" type="date" editType="datepickeredit" visible="true"></e-grid-column>
            <e-grid-column field="FechaMovimiento" headerText="Fecha Movimiento" width="160" minWidth="160" customFormat="@(new { type = "date", format = "dd/MM/yyyy" })" type="date" editType="datepickeredit" visible="true"></e-grid-column>
            <e-grid-column field="FechaAntiguedad" headerText="Fecha Antiguedad" width="160" minWidth="160" customFormat="@(new { type = "date", format = "dd/MM/yyyy" })" type="date" editType="datepickeredit" visible="true"></e-grid-column>
            <e-grid-column field="Debe" headerText="Debe" visible="true" width="190" minWidth="190"></e-grid-column>
            <e-grid-column field="Observaciones" headerText="Observaciones" width="360" minWidth="360" visible="true"></e-grid-column>
        </e-grid-columns>
    </ejs-grid>

//////////////////////////////////////// JAVASCRIPT IN THE VIEW FOR SETTING VALUES ////////////////////////////////////////


    var elem;
    var dObj = @Json.Serialize(ViewBag.ForeignData);

    function create(args) {
        elem = document.createElement('input');
        return elem;
    }

    function read(args) {
        return dObj.value;
    }

    function destroy () {
        dObj.destroy();
    }

    function write (args) {
        dObj = new ej.dropdowns.AutoComplete({
            dataSource: @Html.Raw(Json.Serialize(ViewBag.ForeignData)),
            fields: { value: 'certificado' },
            value: args.rowData[args.column.field],
            change: (e) => {
                   $.ajax({
                    type: 'POST',
                    url: '@Url.Action("FindCertData", "Formatos")',
                    data: {
                        NumCertificado: e.value,
                        FormatoID: @Model.FormatoID
                    },
                       success: function (response) {
                           document.querySelector("#DetalleFormatoAltaGmmVidaApGridNombreAsegurado").value = response._nombreAsegurado;
                           document.querySelector("#DetalleFormatoAltaGmmVidaApGridParentezco").value = response._parentezco;
                           document.querySelector("#DetalleFormatoAltaGmmVidaApGridGender").value = response._Gender;
                           document.querySelector("#DetalleFormatoAltaGmmVidaApGridFechaNacimiento").value = response._fechaNacimiento;
                           document.querySelector("#DetalleFormatoAltaGmmVidaApGridFechaAntiguedad").value = response._fechaAntiguedad;
                    }
                });
            }
        });
        dObj.appendTo(elem);
    }







6 Replies

JA Javier A Aguilera September 3, 2019 08:06 PM UTC

Any luck with this one?


TS Thavasianand Sankaranarayanan Syncfusion Team September 4, 2019 11:37 AM UTC

Hi Javier, 

Thanks for contacting Syncfusion support. 

We have validated the provided code example. Also we have created a sample based on your requirement, please find the code example and sample for your reference. 
 
 
<ejs-grid id="Grid" dataSource="@ViewBag.datasource"  allowPaging="true"  toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })"> 
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editSettings> 
    <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column> 
        <e-grid-column field="CustomerID" headerText="Customer ID" edit="@(new {create = "create", read = "read", destroy = "destroy", write = "write"})" type="string" width="120"></e-grid-column> 
        . . . 
    </e-grid-columns> 
</ejs-grid> 
 
 
 
<script> 
    var elem; 
    var drpObj; 
 
    function create(args) { 
        elem = document.createElement('input'); 
        return elem; 
    } 
 
    function write(args) { 
 
        var grid = document.getElementById('Grid')["ej2_instances"][0]; 
        var data = grid.dataSource; 
            drpObj = new ej.dropdowns.DropDownList({ 
                value: args.rowData[args.column.field], 
                dataSource: data, 
                change: function (args) { 
       
                    var ajax = new ej.base.Ajax("Home/db", "GET"); 
                    ajax.type = 'POST' 
                    ajax.data = JSON.stringify(args.value); 
                    ajax.send(); 
                    ajax.onSuccess = function (data) { 
                 
                        data = JSON.parse(data); 
                        grid.element.querySelector('.e-gridform input#GridFreight').value = data[0]['Freight']; 
                        grid.element.querySelector('.e-gridform input#GridShipCity').value = data[0]['ShipCity']; 
                        grid.element.querySelector('.e-gridform input#GridEmployeeID').value = data[0]['EmployeeID']; 
 
                    }; 
                }, 
                fields: { text: 'CustomerID', value: 'CustomerID' }, 
               
        }); 
            drpObj.appendTo(elem); 
    } 
     
 
        function destroy() { 
            drpObj.destroy(); 
        } 
 
        function read(args) { 
            return drpObj.value; 
        } 
</script> 
 
 
 
In the above sample, we have updated the grid edit form other field values automatically based on “CustomerID” value. 


Still if you have faced same issue again, could you please explain your requirement briefly. 

Regards, 
Thavasianand S. 



JA Javier A Aguilera September 4, 2019 07:46 PM UTC

Good afternoon, 

I'm still facing the same problem, I implemented your code but I still don't get the values in the controller for the CRUD method, here is my current code:


///////////////////////////////////////////VIEW //////////////////////////////////////////
<div id="DetalleGrid">
    <ejs-grid id="DetalleFormatoAltaGmmVidaApGrid" locale="es-MX" query="new ej.data.Query().addParams('IDAlta', '@Model')" toolbar="@(new List<string>() { "Cancel", "Update", "Add", "Delete" })">
        <e-data-manager id="dataManager" adaptor="UrlAdaptor" url="/Sistema/Formatos/DetalleFormatoAltaGmmVidaApGrid_Read/" crudUrl="/Sistema/Formatos/DetalleFormatoAltaGmmVidaApGrid_CRUD" requestType="Post"></e-data-manager>
        <e-grid-editSettings allowDeleting="true" allowEditing="true" allowAdding="true"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="DetalleID" isPrimaryKey="true" isIdentity="true" visible="false"></e-grid-column>
            <e-grid-column field="IDAlta" defaultValue="@Model" visible="false"></e-grid-column>
            <e-grid-column field="Seccion" headerText="Seccion" width="100" minWidth="100"></e-grid-column>
            <e-grid-column field="NumCertificado" headerText="No. Certificado" width="140" minWidth="140" foreignKeyField="certificado" foreignKeyValue="certificado" dataSource="@ViewBag.ForeignData" edit="@(new { create = "create", read = "read", destroy = "destroy", write = "write" })" type="string"></e-grid-column>
            <e-grid-column field="NombreAsegurado" headerText="Nombre del asegurado" width="320" minWidth="320" visible="true"></e-grid-column>
            <e-grid-column field="TipoMovimiento" headerText="Tipo de movimiento" width="190" minWidth="190" visible="true"></e-grid-column>

            <e-grid-column field="Parentezco" headerText="Parentezco" width="140" minWidth="140" foreignKeyField="TipoParentezco" foreignKeyValue="Descripcion" dataSource="@ViewBag.TiposParentezco"></e-grid-column>

            <e-grid-column field="Gender" headerText="Gender" width="146" minWidth="146" foreignKeyField="TipoGender" foreignKeyValue="Descripcion" dataSource="@ViewBag.TiposGender"></e-grid-column>

            <e-grid-column field="FechaNacimiento" headerText="Fecha Nacimiento" width="160" minWidth="160" customFormat="@(new { type = "date", format = "dd/MM/yyyy" })" type="date" editType="datepickeredit" visible="true"></e-grid-column>
            <e-grid-column field="FechaMovimiento" headerText="Fecha Movimiento" width="160" minWidth="160" customFormat="@(new { type = "date", format = "dd/MM/yyyy" })" type="date" editType="datepickeredit" visible="true"></e-grid-column>
            <e-grid-column field="FechaAntiguedad" headerText="Fecha Antiguedad" width="160" minWidth="160" customFormat="@(new { type = "date", format = "dd/MM/yyyy" })" type="date" editType="datepickeredit" visible="true"></e-grid-column>
            <e-grid-column field="Debe" headerText="Debe" visible="true" width="190" minWidth="190"></e-grid-column>
            <e-grid-column field="Observaciones" headerText="Observaciones" width="360" minWidth="360" visible="true"></e-grid-column>
        </e-grid-columns>
    </ejs-grid>
</div>

<script type="text/javascript">
    var elem;
    var dObj = @Json.Serialize(ViewBag.ForeignData);

    function create(args) {
        elem = document.createElement('input');
        return elem;
    }

    function read(args) {
        return dObj.value;
    }

    function destroy () {
        dObj.destroy();
    }

    function write (args) {
        dObj = new ej.dropdowns.AutoComplete({
            dataSource: @Html.Raw(Json.Serialize(ViewBag.ForeignData)),
            fields: { value: 'certificado',  text: 'certificado' },
            value: args.rowData[args.column.field],
            change: (e) => {
                   $.ajax({
                    type: 'POST',
                    url: '@Url.Action("FindCertData2", "Formatos")',
                    data: {
                        NumCertificado: e.value,
                        FormatoID: @ViewBag.FormatoID
                    },
                       success: function (response) {

                           alert(response.nombre);
                           alert(response.parentesco);
                           alert(response.Gender);
                           var gridObj = document.getElementById("DetalleFormatoAltaGmmVidaApGrid")['ej2_instances'][0];
                           gridObj.element.querySelector('.e-gridform input#DetalleFormatoAltaGmmVidaApGridNombreAsegurado').value = response.nombre;
                           gridObj.element.querySelector('.e-gridform input#DetalleFormatoAltaGmmVidaApGridParentezco').value = response.parentesco;
                           gridObj.element.querySelector('.e-gridform input#DetalleFormatoAltaGmmVidaApGridGender').value = response.Gender;
                    }
                });
            }
        });
        dObj.appendTo(elem);
    }
</script>
<ejs-scripts></ejs-scripts>

///////////////////////////////////////////CONTROLLER //////////////////////////////////////////

public IActionResult FindCertData2(int FormatoID, string NumCertificado)
        {
            BeneficiariosFormatoGastosMedicosEmpresarial obj = new BeneficiariosFormatoGastosMedicosEmpresarial();
            
            obj = _context.BeneficiariosFormatoGastosMedicosEmpresarial.FirstOrDefault(p => p.FormatoID == FormatoID && p.certificado == NumCertificado);


            return Json(obj);
        }


[HttpPost]
        public IActionResult DetalleFormatoAltaGmmVidaApGrid_CRUD([FromBody]CRUDModel<DetalleFormatoAltaPolizasGmmVidaAp> obj)
        {
            switch (obj.Action)
            {
                case "insert":
                    _context.DetalleFormatoAltaPolizasGmmVidaAp.Add(obj.Value);
                    break;
                case "update":
                    _context.DetalleFormatoAltaPolizasGmmVidaAp.Attach(obj.Value);
                    _context.Entry(obj.Value).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                    break;
                case "remove":
                    _context.DetalleFormatoAltaPolizasGmmVidaAp.Remove(_context.DetalleFormatoAltaPolizasGmmVidaAp.FirstOrDefault(p => p.DetalleID == Convert.ToInt32(obj.Key)));
                    break;
            }
            _context.SaveChanges();
            return Json(obj.Value);
        }


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team September 5, 2019 02:03 PM UTC

Hi Javier, 
 
Thanks for your update. 
 
Query: I'm still facing the same problem, I implemented your code but I still don't get the values in the controller for the CRUD method 
 
We have validated your query and it works fine at our end. We suspect that whether your controller side code properties are not properly defined. If both controller and view page code is correct, then the actual request response is like in the below screenshots. Please find the request and response for the above action. 
 
[screenshot][while sending selected dropdown data to controller] 
 
 
[screenshot][response from controller] 
 
 
Please ensure that you have defined all properties correctly in the controller side code in your sample. Also ensure that before sending data through ajax, you need to stringify the data. In controller side method, you need to define FromBody attribute. Please find the below code example for your reference. 
 
[code example] 
 
... 
<script> 
    ... 
    function write(args) { 
       var grid = document.getElementById('Grid')["ej2_instances"][0]; 
        var data = grid.dataSource; 
            drpObj = new ej.dropdowns.DropDownList({ 
                value: args.rowData[args.column.field], 
                dataSource: data, 
                change: function (args) { 
                    var obj = {"NumCertificado": args.value, "FormatoID": 21} 
                    var ajax = new ej.base.Ajax("Home/db", "GET"); 
                    ajax.type = 'POST' 
                    ajax.data = JSON.stringify(obj); 
                    ajax.send(); 
                    ajax.onSuccess = function (data) { 
                       data = JSON.parse(data); 
                        ... 
                    }; 
                }, 
              
        });            drpObj.appendTo(elem); 
    } 
            ... 
</script> 
public object DB([FromBodyAttribute] valus val) 
        { 
            var value = val.NumCertificado; 
            var Data = Orders.GetAllRecords(); 
            Data = Data.Where(ord => ord.CustomerID == value).ToList(); 
            return Data; 
        } 
 
        public class valus {  
            public int FormatoID { get; set; } 
            public string NumCertificado { get; set; } 
        } 
 
Note: If any failure occurs during the process, then ajaxfailure method will be triggered. You can get the error details in ajax.OnFailure method. 
 
Please get back to us if you need further assistance. 
 
Regards, 
Seeni Sakthi Kumar S 



JA Javier A Aguilera September 5, 2019 07:39 PM UTC

Thx for your response, I already have working the method for the "write" part, it is the method for the CRUD action the one that I'm still having trouble.

The process is that when I change the value for the column "NumCertificado" the write part put values to theNombreAsegurado, Parentezco, the dates and the Gender, like this:

function write (args) {
dObj = new ej.dropdowns.AutoComplete({
dataSource: @Html.Raw(Json.Serialize(ViewBag.ForeignData)),
fields: { value: 'Certificado', text: 'Certificado' }, /*certificado*/
value: args.rowData[args.column.field],
change: (e) => {
$.ajax({
type: 'POST',
url: '@Url.Action("FindCertData2", "Formatos")',
data: {
NumCertificado: e.value,
FormatoID: @ViewBag.FormatoID,
Tipo: @ViewBag.Tipo
},
success: function (response) {
var gridObj = document.getElementById("DetalleFormatoAltaGmmVidaApGrid")['ej2_instances'][0];
gridObj.element.querySelector('.e-gridform input#DetalleFormatoAltaGmmVidaApGridNombreAsegurado').value = response.nombre;
gridObj.element.querySelector('.e-gridform input#DetalleFormatoAltaGmmVidaApGridParentezco').value = response.parentesco;
gridObj.element.querySelector('.e-gridform input#DetalleFormatoAltaGmmVidaApGridGender').value = response.Gender;
}
});
}
});
dObj.appendTo(elem);
}


The thing is, that when I edited manually the columns I have values in the CRUD action, but when I dont edit manually the record except for the NumCertificado and it put values to the other columsn I have the null values

I already tried in the CRUD action the attributes [FromBody] and [FromBodyAttribute]


In this second image we can see that I'm getting null for the columns that I dont select manually a value (I selected manually the dates).

NOTE: the second null value is the one that I renamed like "Gender" in this post for forum validation purposes.

I know this have been a difficult one, but thanks guys for the hard work!




SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team September 6, 2019 01:24 PM UTC

Hi Javier, 
 
Thanks for your update. 
 
Query: when I edited manually the columns I have values in the CRUD action, but when I dont edit manually the record except for the NumCertificado and it put values to the other columsn I have the null values 
 
We have validated your query and you can resolve the reported problem by using below way. You can assign the data to particular column by getting instance for the particular control element. Please find the below code example and sample for your reference. 
 
[code example] 
... 
 
    function write(args) { 
... 
                value: args.rowData[args.column.field], 
                dataSource: data, 
                change: function (args) { 
                    ... 
                   ajax.onSuccess = function (data) { 
                        data = JSON.parse(data); 
                        grid.element.querySelector('.e-gridform input#GridFreight').ej2_instances[0].value = data[0]['Freight']; //getting instance for numeric textbox and assigned value 
                        grid.element.querySelector('.e-gridform input#GridShipCity').value = data[0]['ShipCity']; 
                        grid.element.querySelector('.e-gridform input#GridOrderDate').ej2_instances[0].value = data[0]['OrderDate']; //getting instance for date picker and assigned value 
                        grid.element.querySelector('.e-gridform input#GridEmployeeID').value = data[0]['EmployeeID'];  
                    }; 
                }, 
                fields: { text: 'CustomerID', value: 'CustomerID' }, 
               
        }); 
            drpObj.appendTo(elem); 
    } 
            ... 
</script> 
 
 
 
If you are still facing the problem, could you please check whether the ModelState is valid or not by using the below code snippets. If you have faced any error, then please share the error details. 
 
public IActionResult Update([FromBody]CRUDModel<Orders> model) 
        { 
            if (!ModelState.IsValid) 
            { 
                return View(); 
            } 
            ... 
           } 
            return Json(model.Value); 
        } 
 
 
If the ModelState is not valid then it throws error like this. 
 
 
 
 

Please get back to us if you need further assistance. 

Regards, 
Seeni Sakthi Kumar S 


Loader.
Live Chat Icon For mobile
Up arrow icon