Articles in this section
Category / Section

How to handle tri-state checkbox in the batch editig in ASP.NET Core Grid?

5 mins read

Grid provides an option edit the Boolean column using Checkbox. Usually, check/uncheck state was provided for editing functionality. To handle the tristate in the checkbox, you have to use the EditTemplate feature of the Grid Columns. Using this ejCheckbox was rendered to handle the intermediate state along with the check/uncheck state. Follow the KB for handling the intermediate state of checkbox in the Batch Editing.

Render the Grid with the EditTemplate to the respective Boolean column, QueryCellInfo and BeforeBatchSave event.

HTML:

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

 

JavaScript:

<script type="text/javascript">
    $(function () {
        $("#Grid").ejGrid({
            dataSource: window.gridData,
            allowPaging: true,
            editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: "batch" },
            toolbarSettings: {
                showToolbar: true,
                toolbarItems: [
                    ej.Grid.ToolBarItems.Add,
                    ej.Grid.ToolBarItems.Edit,
                    ej.Grid.ToolBarItems.Delete,
                    ej.Grid.ToolBarItems.Update,
                    ej.Grid.ToolBarItems.Cancel
                ]
            },
            queryCellInfo: "queryCell",
            beforeBatchSave: "beforeSave",
            columns: [
                    { field: "OrderID", headerText: "Order ID", isPrimaryKey: true, textAlign: ej.TextAlign.Right },
                    { field: "CustomerID", headerText: "Customer ID" },
                    { field: "EmployeeID", headerText: "Employee ID", textAlign: ej.TextAlign.Right },
                    { field: "Freight", format: "{0:C}", textAlign: ej.TextAlign.Right },
                    { field: "OrderDate", headerText: "Order Date", format: "{0:MM/dd/yyyy}", textAlign: ej.TextAlign.Right },
                    { field: "Verified", type: "boolean", editTemplate: { create: "onCreate", write: "onWrite", read: "onRead" } }
            ]
        });
    });
</script>

 

Razor:

@(Html.EJ().Grid<object>("Grid")
    .AllowPaging()
    .Datasource((IEnumerable<object>)ViewBag.dataSource)
    .ClientSideEvents(e =>
    {
        e.QueryCellInfo("queryCell");
        e.BeforeBatchSave("beforeSave");
    })
    .EditSettings(edit => edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch))
    .ToolbarSettings(tools => tools.ShowToolbar().ToolbarItems(items => {
        items.AddTool(ToolBarItems.Add);
        items.AddTool(ToolBarItems.Edit);
        items.AddTool(ToolBarItems.Delete);
        items.AddTool(ToolBarItems.Update);
        items.AddTool(ToolBarItems.Cancel);
    }))
    .Columns(col =>
    {
        col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Add();
        col.Field("CustomerID").HeaderText("Customer ID").Add();
        col.Field("EmployeeID").HeaderText("EmployeeID").TextAlign(TextAlign.Right).Add();
        col.Field("Freight").Format("{0:C}").TextAlign(TextAlign.Right).Add();
        col.Field("Order Date").Format("{0:MM/dd/yyyy}"). HeaderText("Order Date").TextAlign(TextAlign.Right).Add();
        col.Field("Verified").Type("boolean")
            .EditTemplate(eTemp => {
                eTemp.Create("onCreate");
                eTemp.Read("onRead");
                eTemp.Write("onWrite");
        }).Add();
    })
)

 

Controller:

namespace MvcApplication66.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.dataSource = OrderRepository.GetAllRecords();
            return View();
        }
 
    }
}

 

WebForms:

    <ej:Grid ID="Grid" runat="server" AllowPaging="true">
        <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" EditMode="Batch"></EditSettings>
        <ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings>
        <Columns>
            <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="true" TextAlign="Right" />
            <ej:Column Field="CustomerID" HeaderText="Customer ID" />
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" TextAlign="Right" />
            <ej:Column Field="Freight" Format ="{0:C}" TextAlign="Right"/>
            <ej:Column Field="Verified" Type="boolean">
                <EditTemplate Create="onCreate" Read="onRead" Write="onWrite" />
            </ej:Column>
        </Columns>
        <ClientSideEvents QueryCellInfo="queryCell" BeforeBatchSave="beforeSave"  />
    </ej:Grid>

 

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Grid.DataSource = order;
            this.Grid.DataBind();
        }

 

.Net Core

<ej-grid id="Grid" allow-paging="true" toolbar-click="onToolBarClick" query-cell-info="queryCell" before-batch-save="beforeSave" datasource="ViewBag.datasource">
    <e-toolbar-settings show-toolbar="true" toolbar-items=@(new List<string>() { "add", "edit", "delete", "update", "cancel" })></e-toolbar-settings>
    <e-edit-settings allow-adding="true" allow-editing="true" allow-deleting="true"></e-edit-settings>
    <e-columns>
        <e-column field="OrderID" header-text="Order ID" is-primary-key="true" text-align="Right"></e-column>
        <e-column field="EmployeeID" header-text="Employee ID" text-align="Right"></e-column>
        <e-column field="CustomerID" header-text="Customer ID"></e-column>
        <e-column field="Freight" text-align="Right" format="{0:C}"></e-column>
        <e-column field="Verified" type="boolean">
            <e-edit-template create="onCreate" read="onRead" write="onWrite"></e-edit-template>
        </e-column>
    </e-columns>
</ej-grid>

 

namespace core1.Controllers
{
    public partial class GridController : Controller
    {
        public static List<Orders> order = new List<Orders>();
        public ActionResult GridFeatures()
        {
            ViewBag.dataSource = order;
            return View();
        }
    }
}
 

 

Define the Create, Write and Read events of the EditTemplate to create/render/retrieve values from the ejCheckBox to the ejGrid. QueryCellInfo event defined to modify the Native Checkbox element to the ejCheckBox for displaying the intermediate state. BeforeBatchSave event used to set the Boolean values to the respective Boolean column.

<script type="text/javascript">
    function onCreate() {
        return $("<input>");
    }
    function onWrite(args) {
        var val = args.rowdata[args.element.attr("name")];
        var state = val == null ? "indeterminate" : val ? "check" : "uncheck"
        args.element.ejCheckBox({
            checkState: state,
            checked: val,
            enableTriState: true
        });
    }
    function onRead(args) {
        var val = "";
        if (args.hasClass("e-checkbox")) {
            val = args.ejCheckBox("model.checked"), state = args.ejCheckBox("model.checkState");
            val = val ? state == "check" ? true : null : false;
        }
        //create temporary checkbox
        var check = ej.buildTag("input#" + args.attr("name") + Math.round(Math.random() * 1000) + "");
        $("body").append(check);
        check.attr("type", "checkbox")
        check.ejCheckBox({
            checkState: state,
            checked: val,
            enableTriState: true
        });
        //set value in an attribute
        check.attr('ejfieldvalue', val);
        //return ejCheckBox with wrapper
        return check.parent().detach();
    }
    function queryCell(args) {
        if (!$(args.cell).find("input.e-checkbox").length) {
            var field = args.column.field, val = args.data[field] == null ? "indeterminate" : args.data[field] ? "check" : "uncheck";
            $(args.cell).find("input").ejCheckBox({
                checkState: val,
                checked: field,
                enableTriState: true,
                enabled: true
            })
        }
    }
    function beforeSave(args) {
        var c, edited = this.batchChanges.changed;
        for (c = 0 ; c < edited.length; c++) {
            //get saved attribute value
            var val = $(edited[c].Verified.find(".e-checkbox")).attr("ejfieldvalue");
            val = val == "true" ? true : val == "false" ? false : null;
            //set value to fields
            edited[c].Verified = val;
        }
    }
</script>

 

Angular2:

<ej-grid id="Grid" #grid [allowPaging]="true" [editSettings] ="edit" [toolbarSettings]="tools" [dataSource]="datasrc" (queryCellInfo)="queryCell($event)" (beforeBatchSave)="beforeSave($event)">
    <e-columns>
        <e-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="right"></e-column>
        <e-column field="CustomerID" headerText="Customer ID"></e-column>
        <e-column field="EmployeeID" headerText="Employee Name" textAlign="right"></e-column>
        <e-column field="Freight" format="{0:C}" textAlign="right"></e-column>
        <e-column field="OrderDate" headerText="Order Date" format="{0:MM/dd/yyyy}" textAlign="right"></e-column>
        <e-column field="Verified" type="boolean" [editTemplate]="editTemp"></e-column>
    </e-columns>
</ej-grid>

 

TypeScript:

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    constructor() {
        this.datasrc = data;
        this.tools = { showToolbar: true, toolbarItems: ["add", "edit", "delete", "update", "cancel"] };
        this.edit = { allowEditing: true, allowAdding: true, allowDeleting: true, editMode: "batch" };
        this.editTemp = {
            create: function onCreate() {
                return $("<input>");
            },
            write: function onWrite(args) {
                var val = args.rowdata[args.element.attr("name")];
                var state = val == null ? "indeterminate" : val ? "check" : "uncheck"
                args.element.ejCheckBox({
                    checkState: state,
                    checked: val,
                    enableTriState: true
                });
            },
            read: function onRead(args) {
                var val: any, state;
                if (args.hasClass("e-checkbox")) {
                    val = args.ejCheckBox("model.checked"), state = args.ejCheckBox("model.checkState");
                    val = val ? state == "check" ? true : null : false;
                }
                //create temporary checkbox
                var check = ej.buildTag("input#" + args.attr("name") + Math.round(Math.random() * 1000) + "");
                $("body").append(check);
                check.attr("type", "checkbox")
                check.ejCheckBox({
                    checkState: state,
                    checked: val,
                    enableTriState: true
                });
                //set value in an attribute
                check.attr('ejfieldvalue', val);
                //return ejCheckBox with wrapper
                return check.parent().detach();
            }
        };
    }
    public datasrc: any;
    public tools: any;
    public edit: any;
    public editTemp: any;
    @ViewChild('grid') Grid: EJComponents<any, any>;
 
    queryCell(args) {
        if (!$(args.cell).find("input.e-checkbox").length) {
            var field = args.column.field, val = args.data[field] == null ? "indeterminate" : args.data[field] ? "check" : "uncheck";
            $(args.cell).find("input").ejCheckBox({
                checkState: val,
                checked: field,
                enableTriState: true,
                enabled: true
            })
        }
    }
    beforeSave(args) {
        var c, edited = this.Grid.widget.batchChanges.changed;
        for (c = 0; c < edited.length; c++) {
            //get saved attribute value
            var val: any;
            val = $(edited[c].Verified.find(".e-checkbox")).attr("ejfieldvalue");
            val = val == "true" ? true : val == "false" ? false : null;
            //set value to fields
            edited[c].Verified = val;
        }
    }
}
 

 

Figure. Grid with Tristate checkbox in Boolean column


Conclusion

I hope you enjoyed learning about how to handle tri-state checkbox in the batch editing.

You can refer to our ASP.NET Core Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied