Dialog Editing in ASP.NET MVC Grid Component

17 Feb 202324 minutes to read

In dialog edit mode, when you start editing the currently selected row data will be shown on a dialog. You can change the cell values and save edited data to the data source. To enable Dialog edit, set the Mode of EditSettings as Dialog.

@Html.EJS().Grid("DialogEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).Columns(col =>
{
    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = "true"}).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = "true", minLength=3 }).Add();
    col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
    col.Field("ShipName").HeaderText("Ship Name").Width("150").Add();
    col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Customize edit dialog

You can customize the appearance of the edit dialog in the ActionComplete event based on requestType as beginEdit or add.

In the following example, the dialog’s properties like header text, showCloseIcon, height have been changed while editing and adding the records.

Also the locale text for the Save and Cancel buttons has been changed by overriding the default locale strings.

You can refer the Grid Default text list for more localization.

@using Syncfusion.EJ2

@section ControlsSection{
    <div class="control-section">
        @Html.EJS().Grid("DialogTemplateEdit").DataSource((IEnumerable<object>)ViewBag.dataSource).ActionComplete("actionComplete").Columns(col =>
   {
       col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
       col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();
       col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width("150").Add();
   }).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
    </div>
   
    <script>

         ej.base.L10n.load({
            'en-US': {
                'grid': {
                    'SaveButton': 'Submit',
                    'CancelButton': 'Discard'
                }
            }
        });

        function actionComplete(args) {
            if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
                var dialog = args.dialog;
                dialog.showCloseIcon = false;
                dialog.height = 400;
                // change the header of the dialog
                dialog.header = args.requestType === 'beginEdit' ? 'Edit Record of ' + args.rowData['CustomerID'] : 'New Customer';
            }
        }
    </script>
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

The Grid add or edit dialog element has the max-height property, which is calculated based on the available window height. So, in the normal window (1920 x 1080), it is possible to set the dialog’s height up to 658px.

Show or hide columns in dialog editing

The Grid has the option to show hidden columns or hide visible columns while editing in the dialog edit mode by using the ActionBegin event of the Grid.

In the ActionBegin event, when the requestType is beginEdit or add, the column will be shown or hidden using the Visible property of Column. When the requestType is save, the properties will be reset to their original state.

In the following example, the CustomerID column is rendered as a hidden column, and the ShipCountry column is rendered as a visible column. In the edit mode, the CustomerID column will be changed to a visible state and the ShipCountry column will be changed to a hidden state.

@using Syncfusion.EJ2

@Html.EJS().Grid("DialogTemplateEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).ActionBegin("actionBegin").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").Visible(false).Add();
   col.Field("Freight").HeaderText("Freight").EditType("numericedit").Format("C2").Width("150").Add();
   col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

<script>
    function actionBegin(args) {
        if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
            for (var i = 0; i < this.columns.length; i++) {
               if (this.columns[i].field == "CustomerID") {
                   this.columns[i].visible = true;
               }
               else if (this.columns[i].field == "ShipCountry") {
                   this.columns[i].visible = false;
               }
            }
        }
         if (args.requestType === 'save') {
            for (var i = 0; i < this.columns.length; i++) {
                if (this.columns[i].field == "CustomerID") {
                    this.columns[i].visible = false;
                }
                else if (this.columns[i].field == "ShipCountry") {
                    this.columns[i].visible = true;
                    }
                }
        }
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Use wizard like dialog editing

Wizard helps you create intuitive step-by-step forms to fill. You can achieve the wizard like editing by using the dialog template feature. It support your own editing template by defining Mode of EditSettings as Dialog and Template as SCRIPT element ID or HTML string which holds the template.

The following example demonstrate the wizard like editing in the grid with the obtrusive Validation.

@Html.EJS().Grid("DialogTemplateEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).ActionComplete("actionComplete").Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
   col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();
   col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width("150").Add();

}).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog).Template("#dialogtemplate"); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()
    

<script>
     function actionComplete(args) {
         if ((args.requestType === 'beginEdit' || args.requestType === 'add')) {
            var countryData = ej.data.DataUtil.distinct(this.dataSource, 'ShipCountry', true);
                new ej.dropdowns.DropDownList({
                    value: args.rowData.ShipCountry, popupHeight: '300px', floatLabelType: 'Always',
                    dataSource: countryData, fields: { text: 'ShipCountry', value: 'ShipCountry' }, placeholder: 'Ship Country'
                }, args.form.elements.namedItem('ShipCountry'));
                new ej.buttons.CheckBox({ label: 'Verified', checked: args.rowData.Verified }, args.form.elements.namedItem('Verified'));
                // Set initail Focus
                if (args.requestType === 'beginEdit') {
                    (args.form.elements.namedItem('CustomerID')).focus();
                }
                initializeWizard();
            }
    }

    function initializeWizard() {
        var currentTab = 0;

        document.getElementById('nextBtn').onclick = function () {
            var grid = document.getElementById("DialogTemplateEdit").ej2_instances[0];
            var valid = true;
            [].slice.call(document.getElementById('tab' + currentTab).querySelectorAll('[name]')).forEach(element => {
                element.form.ej2_instances[0].validate(element.name);
                if (element.getAttribute('aria-invalid') === 'true') {
                    valid = false;
                }
            });
            if (!valid) {
                return
            }
            if (this.innerHTML !== 'SUBMIT') {
                currentTab++;
                nextpre(currentTab);
            } else {
                grid.endEdit();
            }
        }

        document.getElementById('prevBtn').onclick = function () {
            var valid = true;
            [].slice.call(document.getElementById('tab' + currentTab).querySelectorAll('[name]')).forEach(element => {
                element.form.ej2_instances[0].validate(element.name);
                if (element.getAttribute('aria-invalid') === 'true') {
                    valid = false;
                }
            });
            if (!valid) {
                return
            }
            currentTab--;
            nextpre(currentTab);
        }

        function nextpre(current) {
            var tabs = [].slice.call(document.getElementsByClassName('tab'))
            tabs.forEach(element => element.style.display = 'none');
            tabs[current].style.display = '';
            if (current) {
                document.getElementById('prevBtn').style.display = '';
                document.getElementById('nextBtn').innerHTML = 'SUBMIT';
            } else {
                document.getElementById('prevBtn').style.display = 'none';
                document.getElementById('nextBtn').innerHTML = 'NEXT';
            }
        }
    }
 </script>

 <script id='dialogtemplate' type="text/x-template">
     <div>
        <div id="tab0" class='tab'>
           <div class="form-row">
              <div class="form-group col-md-6">
                 <div class="e-float-input e-control-wrapper">
                    <input id="OrderID" required name="OrderID" type="text" value="${if(isAdd)} '' ${else} ${OrderID} ${/if}" disabled="${if(isAdd)} '' ${else} disabled ${/if}" />
                    <span class="e-float-line"></span>
                    <label class="e-float-text e-label-top" for="OrderID">Order ID</label>
                 </div>
              </div>
           </div>
           <div class="form-row">
              <div class="form-group col-md-6">
                 <div class="e-float-input e-control-wrapper">
                    <input id="CustomerID" required name="CustomerID" type="text" value="${if(isAdd)} '' ${else} ${CustomerID} ${/if}" />
                    <span class="e-float-line"></span>
                    <label class="e-float-text e-label-top" for="CustomerID">Customer ID</label>
                 </div>
              </div>
           </div>
        </div>
        <div id=tab1 style="display: none" class='tab'>
           <div class="form-row">
              <div class="form-group col-md-6">
                 <input type="text" name="ShipCountry" id="ShipCountry" value="${if(isAdd)} '' ${else} ${ShipCountry} ${/if}" />
              </div>
            </div>
            <div class="form-row">
               <div class="form-group col-md-6">
                  <input type="checkbox" name="Verified" id="Verified" checked="${if(Verified)} checked ${/if}" />
               </div>
             </div>
         </div>
         <div id='footer'>
            <button id="prevBtn" class="e-info e-btn" type="button" style="display: none; float: left; margin-left: 11px;">Previous</button>

            <button id="nextBtn" class="e-info e-btn" type="button" style="float: right">Next</button>
          </div>
    </div>
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

In dialog edit mode, a dialog will show up when editing the currently selected row or adding a new row. By default, you can save or cancel the edited changes by clicking the Save or Cancel button in the dialog’s footer. Along with these buttons, it is possible to add a custom button in the footer section using the ActionComplete event of the Grid.

In the following sample, using the dialog argument of the ActionComplete event, the action for the custom button can be customized.

@Html.EJS().Grid("DialogTemplateEdit").DataSource((IEnumerable<object>)ViewBag.DataSource).ActionComplete("actionComplete").Columns(col =>
   {
       col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").ValidationRules(new { required = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
       col.Field("CustomerID").HeaderText("Customer Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();
       col.Field("ShipCountry").HeaderText("Ship Country").EditType("dropdownedit").Width("150").Add();
   }).AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Dialog); }).Toolbar(new List<string>() { "Add", "Edit", "Delete" }).Render()
 
<script>
    function actionComplete(args) {
        if (args.requestType === 'beginEdit' || args.requestType === 'add') {
            let newFooterButton = {
                buttonModel: { content: 'custom' },
                click: onCustomButtonClick
            };
            args.dialog.buttons.push(newFooterButton);
            args.dialog.refresh();
        }
    }
    function onCustomButtonClick() {
        alert('Add/Edit dialog custom footer button clicked');
    }
</script>
public IActionResult Index()
 {
   var orders= OrderDetails.GetAllRecords();
   ViewBag.DataSource = orders;            
   return View();
 }