Search
Sunday 20 January 2019
  • :
  • :

How to Develop Kendo Window Popup with Grid CRUD Operation in MVC

This post will help you in understanding the steps for developing Kendo Window Popup with CRUD operation in asp.net MVC development. You will learn about the Kendo and its uses and major advantages. Read further for more info.

Here we explain how to use and perform CRUD operation in Kendo Grid in Kendo Window popup in MVC based application. Keno UI is an Html5, jQuery-based framework for building modern web application. Kendo Window popup is used for display data in popup above grid or anywhere where required and grid is use for binding data.

Kendo Window Pop up

Below are the steps for how to use Kendo UI in MVC.

  1. Download the Kendo UI JavaScript :-

Download Trial version of Kendo JavaScript and css, for download click here.

  1. Add Kendo UI JavaScript and Css References :-

For give the Kendo UI reference of JavaScript and css we need to write below code in MVC view.Set reference of Kendo UIJavaScript in MVC view and then call the Html Kendo grid () function where we need.Show the JavaScript code as per below.

<scriptsrc="~/ReportJS/jquery.min.js"></script>
<scriptsrc="~/ReportJS/kendo.all.min.js"></script>
<scriptsrc="~/ReportJS/kendo.aspnetMVC.min.js"></script>
<scriptsrc="~/ReportJS/console.js"></script>

<linkhref="~/css/kendo.common.min.css"rel="stylesheet">
<linkhref="~/css/kendo.rtl.min.css"rel="stylesheet">
<linkhref="~/css/kendo.default.min.css"rel="stylesheet">
<linkhref="~/css/kendo.dataviz.min.css"rel="stylesheet">
<linkhref="~/css/kendo.dataviz.default.min.css"rel="stylesheet">

 As per above code we can give the reference for Kendo UI JavaScript and CSS from project location.

  1. Kendo Window Popup and Grid Binding code in view :-

After completing the process of add kendo UI reference we use that for display popup and data banding. So for that we have use Html kendo window popup and grid function of Kendo UI JavaScript.

We bind the grid column and bind the data from controller method by Json value also give the required value parameter Like Name etc. And set the configuration for grid like we have to display or Enable-disable paging, sorting, scrolling, and filtering in grid.

For that setpageable (), sortable (), scrollable () and filterable () propertyof grid. Also if we want to perform operation in server side then we have to give ServerOperation true for the Kendo UI grid. In kendo UI grid we set the custom format for date or set custom size for columns or give the link to other pages using client template. Here Implement the kendo UI grid as per given below code.

Here are the Div in which we display kendo grid and KendoWindow popup.

<divid="DetailsDb"><divid="Grid"style="height: 430px;"></div></div>
<divid="kWindowEmpty"style="display:none"></div>
<divid="MyDivContEdit"style="display:none">
<divid="OpenEdit"style="display:none"></div>
</div>

Here we have createDataSource() function in which we  bind the data for grid and pass this to datasource of grid.

functioncreateDataSource() {
returnnewkendo.data.DataSource({
transport: {
read: {
url: "@Url.Action("LoadData", "Detail")",
data: additionalData,
cache: false
                            },
                        },
schema: {
data: "Data",
total: "Total"
                        },
pageSize: 20,
serverPaging: true,
serverFiltering: false,
serverSorting: false
                    });
                }
var ds = createDataSource();

Now Here we bind the Grid as per below code and Grid have button for edit the record in popup in which we have to bind another grid in kendo Popup and perform CRUD operation for that Popup Grid.

            $("#Grid").kendoGrid({
autoBind: true,
filterable: false,
dataSource: ds,
columns: [
                        {
title: "ID",
type: "string",
width: 150,
field: "Id",
hidden: true
                        },
                        {
title: "@Resource.Row",
type: "string",
width: 50,
field: "LineNum"
                        },
                        {
field: "CodProd",
title: "@Resource.ProductCode",
type: "string",
width: 120
                        },
                        {
field: "ProdDescription",
title: "@Resource.Description",
type: "string",
width: 100
                        },
                        {
field: "BatchCod",
title: "@Resource.Batch",
type: "string",
width: 85
                        },
                        {
field: "Quantity",
title: "@Resource.Quantity",
type: "string",
width: 70
                        },
                        {
field: "UnitMeasure",
title: "@Resource.UM",
type: "string",
width: 50
                        },
                        {
field: "QuantityBase",
title: "@Resource.QuantityBase",
type: "string",
width: 70
                        },
                        {
field: "UnitaMisuraBase",
title: "@Resource.UMbase",
type: "string",
width: 50
                        },
                        {
field: "SystemNUDC",
title: "@Resource.SystemNUDC",
type: "string",
width: 65
                        },
                        {
field: "SystemQtyXUDC",
title: "@Resource.SystemQtyXUDC",
type: "string",
width: 70
                        },
                        {
command: [
                                {
name: 'Edit',
text: "Edit",
click: OpenEdit2
}
                            ],
title: "@Resource.Labels",
width: 152
                        },
                        {
field: "UDCId",
title: "@Resource.UdcId",
type: "string",
width: 170
                        }
                    ],
groupable: false,
pageable: true,
scrollable: true,
sortable: false
                });

After complete code for bind grid date we have to edit that record in Kendo window Popup so for that we have to open and validate that record in kendo Popup as per below code.

//EDIT
                $("#OpenEdit").kendoWindow({
actions: ["Maximize", "Close"],
visible: false,
modal: true,
close: onCloseOpenEdit
                });
var id;
function OpenEdit2(e) {
e.preventDefault();
vartr = $(e.target).closest("tr");
if (!tr) {
if (console)
console.log("OpenEdit Id is null");
return;
                    }
vardatax = this.dataItem(tr);
if (!datax) {
if (console)
console.log("OpenEditdatax is null");
return;
                    }
if (console)
console.log("OpenEdit for: " + datax.Id);
varurlEdit = "@Url.Action("EditUDC", "Detail")/";
varEditTitle = "@Resource.UC610EditWinTitle";
id = datax.Id;
varmyWin = $("#OpenEdit");
try {
if (!myWin.data("kendoWindow")) {
// window not yet initialized
myWin.kendoWindow({
actions: ["Maximize", "Close"],
visible: false,
modal: true,
close: onCloseOpenEdit
                            });
                        } else {
// reopening window
var wnde2 = myWin.data("kendoWindow");
wnde2.title(EditTitle);
wnde2.content($("#kWindowEmpty").html());
wnde2.refresh();
wnde2.setOptions({
width: "90%",
height: "80%"
                            });
            wnde2.refresh(
             {
            url: urlEdit,
            data: { Id: datax.Id }
                            });
if (wnde2) {
wnde2.center();
wnde2.open();
                            } else {
if (console)
console.log("OpenEdit wnde2 is null");
                            }
                        }
                    } catch (er) {
if (console)
console.log("error:" + er.message);
                    }
                }

Here we write the code for Kendo Popup window close event method to perform the validation for main grid, so onclose event we have to perform that validation and update the data as we have update in Popup. Using refresh function we can refresh popup window.

functiononCloseOpenEdit(e) {
e.preventDefault();
                $.ajax({
method: 'POST',
url: ‘@Url.Action("ConfirmCloseValidate","Detail")/?Id='+ id,
context: document.body
                    }).done(function (result) {
if (result != "") {
                            $(".confirmclosemsg").text(result);
                            $("#ConfirmAndClosedialog").show();
                            $("#btnCCDialogNO").click(function () {
e.preventDefault();
                                $(".confirmclosemsg").text('');
                                $("#ConfirmAndClosedialog").hide();
returnfalse;
                            });
                            $("#btnCCDialogYES").click(function () {
                                $(".confirmclosemsg").text('');
                                $("#ConfirmAndClosedialog").hide();
if (console)
console.log("OpenEdit is closed");
try {
                                    $('.k-overlay').hide();
                                    $('.k-window').hide();
var grid = $("#Grid");
                        if (grid) {
            vargridsource = $("#Grid").getKendoGrid();
if (gridsource) {
grid.dataSource = ds;
ds.read();
                                        }
else {
if (console)
console.log("OpenEdit: gridsource is null");
                                        }
                                    } else {
if (console)
console.log("OpenEdit: grid is null");
                                    }
                                } catch (Error1) {
if (console)
console.log("Error:" + Error1);
                                }
returnfalse;
                            });
e.preventDefault();
                        }
                    });
                }

In above code LoadData action is call inDetailcontroller and in which parameter is passed by Data property of grid using JavaScriptfunction as per below code. Here we define the additionalData function for pass the data for parameter to load the grid.

functionadditionalData() {
return {
Id: $('#Id').val()
};
        }

4. Controller Action method for fill data in Grid and Kendo Popup grid :-

Below are the Controller action methods for fill the data in grid, for fill the main grid LoadData action method is called and for fill popup grid method is called in controller as shown in below code.

///<summary>
///Used to bind DDTDetails Grid
///</summary>
///<param name="request">is data request</param>
///<param name="numcod">is numcod</param>
///<param name="NoteId">is NoteId</param>
///<returns>detail view</returns>
publicActionResultLoadData([DataSourceRequest]DataSourceRequestrequest, longnumcode, GuidNoteId)
        {
List<DeliveryNoteDet> list = newList<DeliveryNoteDet>();
try
            {
int count = 0;
if (request.PageSize == 0)
                {
request.PageSize = session.PageSize;
                }
list = DeliveryNoteDet.GetAseDeliveryNoteDetPagewise(numcode, NoteId, request.Page, request.PageSize);
count = DeliveryNoteDet.GetAseDeliveryNoteDetCount(numcode, NoteId);
list = (from a inlist.OrderByDescending(x =>x.LineNum)
selectnewDeliveryNoteDet
                        {
IdNoteDet = a.IdNoteDet,
LineNum = a.LineNum,
CodProd = a.CodProd,
                            Description = a.Description,
BatchCod = a.BatchCod,
                            Quantity = a.Quantity,
UnitMeasureCod = a.UnitMeasureCod,
QuantityBase = a.QuantityBase,
UnitaMisuraBase = a.UnitaMisuraBase,
                            ProdDescription2 = a.ProdDescription2,
CodContainer = a.CodContainer,
NumOrdine = a.NumOrdine,
PackNum = a.PackNum,
Progr = a.Progr,
RootCauseCod = a.RootCauseCod,
RootCauseDescription = a.RootCauseDescription,
SerialNumber = a.SerialNumber,
                            UPC = a.UPC,
LocationName = a.LocationName,
FreePassProd = a.FreePassProd,
BatchCodVendor = a.BatchCodVendor,
DataScadenza = a.DataScadenza,
DdtVenditaReso = a.DdtVenditaReso,
SystemQtyXUDC = this.GetQuantityByProduct(a.CodProd),
UDCId= this.GetUDCRecordByIdDeliveryNoteDet(a.IdDeliveryNoteDet),
SystemNUDC = this.GetSystemUDCQty(a.CodProd, a.QuantityBase)
                        }).ToList();
if (list == null)
list = newList<DeliveryNoteDet>();
var result = newDataSourceResult()
                {
                    Data = list,
                    Total = count
                };
returnJson(result, JsonRequestBehavior.AllowGet);
            }
catch (Exception ex)
            {
if (log.IsErrorEnabled)
log.Error(ex.Message, ex);
returnJson(list, JsonRequestBehavior.AllowGet);
            }
        }

Here In above action method we got the list of DeliveryNoteDet data in List that convert into Json format that pass in view, result display as per below screenshots.

#region Edit
privateconstString C_UC610EDIT_VIEW = @"~/Views/UC610/Edit.cshtml";
publicActionResultEditUDC(Models.InBound.InBoundUC610DTOpPayload)
        {
UC610EditViewModel __VWM = newUC610EditViewModel();
            __VWM.SetDefault();
InBoundService __srvInBoundService = null;
Tuple<bool, Exception, UC610EditViewModel> __tRet;
try
            {
if (!ModelState.IsValid)
                {
                    __VWM = newUC610EditViewModel();
                    __VWM.SetMessage(String.Format(Resource.CommonResource.ModelStateIsNotValid, ""));
                }
else
                {
    __srvInBoundService = newInBoundService(RepoSqlSessionWA.createInstance().getCurrentSqlSession());
__tRet = __srvInBoundService.createUC610EditViewModel(pPayload, Language, LoginUser.IdContact);
if (__tRet.Item1)
                    {
                        __VWM = __tRet.Item3;
                    }
else
                    {
AseLoggingUtil.LogSimpleError(log, __tRet.Item2.Message, null, __tRet.Item2);
                        __VWM.SetMessage(String.Format(Resource.CommonResource.CommonExceptionMessage, __tRet.Item2.Message));
                    }
                }
            }
catch (Exception ex)
            {
                __VWM = newUC610EditViewModel();
__VWM.SetMessage(String.Format(Resource.CommonResource.CommonExceptionMessage, ex.Message));
AseLoggingUtil.LogSimpleError(log, ex.Message, null, ex);
            }
return View(C_UC610EDIT_VIEW, __VWM);
        }

Above is the code for Open Kendo window popup with grid data. If we have any data then we can update that data inline in Kendo popup grid as per below code.

       [AcceptVerbs(HttpVerbs.Post)]
publicActionResultEditingInline_Update([DataSourceRequest] DataSourceRequest request, AseCommonCoreModel.Inbound.InboundARDCpItem)
        {
InBoundService __srvInBoundService = null;
Tuple<bool, Exception, String, AseCommonCoreModel.Inbound.InboundARDC> __tRet;
if (pItem != null&&ModelState.IsValid)
            {
//
  __srvInBoundService = newInBoundService(RepoSqlSessionWA.createInstance().getCurrentSqlSession());
__tRet = __srvInBoundService.UpdateInboundARDCItem(pItem, LoginUser.IdContact);
if (!__tRet.Item1)
                {
ModelState.AddModelError("Entity", __tRet.Item3);
                }
pItem = __tRet.Item4;
            }
else
            {
ModelState.AddModelError("Entity", InboundResource.UC610EditEntityIsNotValid);
            }
returnJson(new[] { pItem }.ToDataSourceResult(request, ModelState));
        }

For Create new Record in grid we have add New Record button in kendo grid, so as per below code we can add new record in grid.

        [AcceptVerbs(HttpVerbs.Post)]
publicActionResultEditingInline_Create([DataSourceRequest] DataSourceRequest request, AseCommonCoreModel.Inbound.InboundARDCpItem)
        {
InBoundService __srvInBoundService = null;
Tuple<bool, Exception, String, AseCommonCoreModel.Inbound.InboundARDC> __tRet;
if (pItem != null&&ModelState.IsValid)
            {
//
__srvInBoundService = newInBoundService(RepoSqlSessionWA.createInstance().getCurrentSqlSession());
__tRet = __srvInBoundService.CreateInboundARDCItem(pItem, session.LoginUser.IdContact);
if (!__tRet.Item1)
                {
ModelState.AddModelError("Entity", __tRet.Item3);
                }
pItem = __tRet.Item4;
            }
else
            {
ModelState.AddModelError("Entity", InboundResource.UC610EditEntityIsNotValid);
            }
returnJson(new[] { pItem }.ToDataSourceResult(request, ModelState));
        }

Also if we want to delete that record then we can delete record by confirmation of user as per below code.

///<summary>
///EditingInline_Destroy Use for Updat Resource &ResourceDocument
///</summary>
///<param name="ResourceCod"></param>
///<returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
publicActionResultEditingInline_Destroy(stringResourceCod)
        {
InBoundService __srvInBoundService = null;
Tuple<bool, Exception> __tRet = null;
if (ResourceCod != null)
            {
                __srvInBoundService = newInBoundService(RepoSqlSessionWA.createInstance().getCurrentSqlSession());
__tRet = __srvInBoundService.DeleteInboundARDCItem(ResourceCod, LoginUser.IdContact);
            }
returnJson(__tRet != null&& __tRet.Item1);
        }

Also we can perform validation for Kendo Popup close or not by user. If close then validate qty value of popup grid with main grid and set validation message for that.

///<summary>
///ConfirmAndCloseValidation
///</summary>
///<param name="IdDeliveryNoteDet">is IdDeliveryNoteDet</param>
///<returns>Validation</returns>
publicActionResultConfirmAndCloseValidation(GuidIdDeliveryNoteDet)
        {
InBoundService __srvInBoundService = null;
Tuple<string, Exception> __tRet = null;
if (IdDeliveryNoteDet != null)
            {
__srvInBoundService = newInBoundService(RepoSqlSessionWA.createInstance().getCurrentSqlSession());
                __tRet = __srvInBoundService.CheckQuantityBase(IdDeliveryNoteDet);
            }
returnJson(__tRet.Item1);
        }
        #endregion Edit
  1. Result of the Kendo Window Popup and Grid:
    1. Kendo UI Detail (Main)Grid Data Load:-Kendo UI Detail (Main)Grid Data Load
    2. Kendo window open On Edit button of Main Grid:-Kendo window open On Edit button of Main Grid
    3. CRUD operation performs on Kendo Popup and Inline editing:-CRUD operation performs on Kendo Popup and Inline editing
    4. Delete popup grid record by confirmation message:-Delete popup grid record by confirmation message
  1. Advantages of Kendo Grid and Kendo Popup.
    1. Ultimateperformance gives to UI with minimum resources and easy to use in MVC based application.
    2. Here In Kendo UIwe use Data Source component is an abstraction for using local (arrays of JavaScript objects) or remote (XML, JSON, JSONP) data. It fully supports CRUD (create, read, update, delete) data operations and provides both local and server-side support for sorting, paging, filtering, grouping, and aggregates.
    3. Also using kendo popup we can perform the CRUD Operation of two more tables those are related with each other in single page.

Hope you have understood every step discussed in this post. Do share your asp.net MVC development experience with us and tell us if you encounter any issue. You will get response from the experts.



Vijay is a compulsive blogger who likes to educate like-minded people on various new technologies and trends. He works with Aegis SoftTech as a software developer and has been developing software for years. Stay Connected to him on Facebook and Google+.