- Home
- Forum
- ASP.NET Core - EJ 2
- How to Add Command to data Grid toolbar to be as custom edit for editing some specific data?
How to Add Command to data Grid toolbar to be as custom edit for editing some specific data?
Hi,
Q- How to Add Command to data Grid toolbar to be as custom edit for editing some specific data with default Edit Command?
(Note: It will be 2 Edit commands , the first Edit will be the default edit but the second edit will be custom edit for some data only
The Custom Edit Content will be partial view like default Add and default Edit Template ).
Thanks Very much
- Are you want to use default edit button and custom edit button in the toolbar? Like (“Edit – default edit button”, “CustomEdit – custom button”)
- Do you want to handle both the default edit and custom edit in the Grid?
- Do you want to use our inbuild CRUD actions with CustomEdit button or Do you want to handle your own CRUD action in custom edit?
- Which type of Editing you want to use for default Edit button and CustomEdit button (Inline/ Dialog/ Dialog Template)?
- Share the full Grid code files.
Hi Rajapandiyan Settu ,
Thanks for response,
1- Yes, This is absolutely true ,I want (“Edit – default edit button”, “CustomEdit – custom button”).
2- Yes, This is absolutely true.
3- I want to handle your own CRUD action in custom edit, but if you teach me the two method ,that would be kind of you.
4- I want to use Dialog Template Edit.
5-
In Main View
Grid
<ejs-grid id="Grid" actionBegin="actionBegin" actionFailure="actionFailure" allowPaging="true" allowResizing="true"
allowSorting="true" allowFiltering="true" allowMultiSorting="true" allowReordering="true"
toolbar="@(new List<string>() { "Add","Edit", "Delete","Update","Cancel" })" actionComplete="actionComplete" created="created" load="onLoad">
<e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" allowEditOnDblClick="false" showConfirmDialog="true" showDeleteConfirmDialog="true" mode="Dialog" template='#dialogtemplate'></e-grid-editSettings>
<e-grid-pagesettings pageSize="10" pageSizes="true"></e-grid-pagesettings>
<e-grid-filtersettings type="Excel"></e-grid-filtersettings>
@*<e-data-manager url="/Home/UrlDataSource" adaptor="UrlAdaptor" insertUrl="/Home/Insert" updateUrl="/Home/Update" removeUrl="/Home/Remove"></e-data-manager>*@
<e-grid-columns>
<e-grid-column field="ID" headerText="ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
<e-grid-column field="FullName" headerText="@ResourcesWeb.PayrollResource.FullName" validationRules="@(new {required=true})" width="200" minWidth="180" maxWidth="400">
</e-grid-column>
<e-grid-column field="AliasName" headerText="@ResourcesWeb.PayrollResource.AliasName" validationRules="@(new {required=true })" width="200" minWidth="180" maxWidth="250">
</e-grid-column>
<e-grid-column field="EmpCode" headerText="@ResourcesWeb.PayrollResource.EmpCode" validationRules="@(new {required=true})" width="180" minWidth="150" maxWidth="200">
</e-grid-column>
<e-grid-column field="Email" headerText="@ResourcesWeb.PayrollResource.Email" validationRules="@(new {required=true})"
width="200" minWidth="180" maxWidth="400">
</e-grid-column>
<e-grid-column field="ReligionID" headerText="@ResourcesWeb.PayrollResource.ReligionName" validationRules="@(new {required=true })"
dataSource="@(IEnumerable<object>)ViewBag.Religions" foreignKeyField="ID" foreignKeyValue="Name"
width="200" minWidth="180" maxWidth="400" EditType="dropdownedit">
</e-grid-column>
<e-grid-column field="RoleID" headerText="@ResourcesWeb.PayrollResource.RoleTitle" validationRules="@(new {required=true })"
dataSource="@(IEnumerable<object>)ViewBag.Roles" foreignKeyField="Id" foreignKeyValue="Name"
width="200" minWidth="180" maxWidth="400" EditType="dropdownedit">
</e-grid-column>
<e-grid-column field="IsResigned" headerText="@ResourcesWeb.PayrollResource.IsResigned" width="200" minWidth="180" maxWidth="400">
</e-grid-column>
</e-grid-columns>
</ejs-grid>
<script id='dialogtemplate' type="text/x-template">
<div id="dialogTemp">
</div>
</script>
<script type="text/javascript">
function actionBegin(args) {
if (args.requestType === 'save') {
console.log(args);
}
}
function actionFailure(args) {
console.log(args);
}
function onLoad() {
//this.dataSource.dataSource.headers = [{ 'XSRF-TOKEN': $("input:hidden[name='__RequestVerificationToken']").val() }];
document.getElementsByClassName('e-grid')[0].addEventListener("click", (args) => {
if (args.target.classList.contains("e-file-cancel")) {
var grid = ej.grids.parentsUntil(args.target, 'e-grid').ej2_instances[0];
var selectedRecords = grid.getSelectedRecords();
if (selectedRecords.length > 0) {
var OrderIDVal = selectedRecords[0];
/* console.log(OrderIDVal)*/
// ParentTask_DDL2.Value = OrderIDVal;
// console.log(ParentTask_DDL2.value);
// var numericTextBoxInstance = document.getElementById("TreeGrid_gridcontrolParentTaskID");
//console.log(numericTextBoxInstance);
//numericTextBoxInstance.innerText = OrderIDVal;
ParentTask_DDL.value = OrderIDVal
console.log(ParentTask_DDL.value);
}
var rowObj = grid.getRowObjectFromUID(ej.grids.parentsUntil(args.target, 'e-row').getAttribute('data-uid'));
var data = rowObj.data;
console.log(data);
var dialog = new ej.popups.Dialog({
showCloseIcon: true,
header: "Show ID",
target: document.getElementsByClassName("e-grid")[0],
width: '250px'
});
// Render initialized Dialog
dialog.appendTo('#dialog');
dialog.content = 'Email : ' + data.Email;
dialog.show();
}
})
}
function actionComplete(args) {
console.log(args);
if (args.requestType === 'beginEdit' || args.requestType === 'add' || args.requestType === 'Resign') {
args.dialog.width = "60%";
let spinner = ej.popups.createSpinner({ target: args.dialog.element });
ej.popups.showSpinner(args.dialog.element);
if (args.requestType === 'beginEdit') {
var ajax = new ej.base.Ajax({
url: "@Url.Action("Editpartial", "Employee")", //render the partial view
type: "POST",
contentType: "application/json",
data: JSON.stringify({ value: args.rowData })
});
ajax.send().then(function (data) {
appendElement(data, args.form); //Render the edit form with selected record
args.form.elements.namedItem('FullName').focus();
ej.popups.hideSpinner(args.dialog.element);
}).catch(function (xhr) {
console.log(xhr);
ej.popups.hideSpinner(args.dialog.element);
});
}
if (args.requestType === 'add') {
var ajax = new ej.base.Ajax({
url: "@Url.Action("Addpartial", "Employee")", //render the partial view
type: "POST",
contentType: "application/json",
data: JSON.stringify({ value: args.rowData })
});
ajax.send().then(function (data) {
appendElement(data, args.form); //Render the edit form with selected record
args.form.elements.namedItem('FullName').focus();
ej.popups.hideSpinner(args.dialog.element);
}).catch(function (xhr) {
console.log(xhr);
ej.popups.hideSpinner(args.dialog.element);
});
}
}
}
function appendElement(elementString, form) {
form.querySelector("#dialogTemp").innerHTML = elementString;
var script = document.createElement('script');
script.type = "text/javascript";
var serverScript = form.querySelector("#dialogTemp").querySelector('script');
script.textContent = serverScript.innerHTML;
document.head.appendChild(script);
serverScript.remove();
}
</script>
Add Partial View
@model AssembleWeb.ViewModel.Payroll.Employees.EmployeeViewModel
@*//define the model for store the model values*@
@using Syncfusion.EJ2
<div>
<div class="form-row">
<div class="form-group col-md-12">
<div class="e-float-input e-control-wrapper">
<input asp-for="ID" type='text' hidden="hidden" value="0" />
<span class="e-float-line"></span>
<label asp-for="ID" hidden="hidden" class="e-float-text e-label-top text-dark">ID</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="FullName" type="text" />
<span class="e-float-line"></span>
<label asp-for="FullName" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="AliasName" type="text" />
<span class="e-float-line"></span>
<label asp-for="AliasName" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="AliasName" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="Email" type="email" />
<span class="e-float-line"></span>
<label asp-for="Email" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="Password" type="password" />
<span class="e-float-line"></span>
<label asp-for="Password" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="EmpCode" type="text" />
<span class="e-float-line"></span>
<label asp-for="EmpCode" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="EmpCode" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="PhoneNo" type="tel" />
<span class="e-float-line"></span>
<label asp-for="PhoneNo" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="PhoneNo" class="text-danger"></span>
</div>
</div>
</div>
</div>
<ejs-scripts></ejs-scripts>
In Controller
public class EmployeeController : BaseController
{
// GET: EmployeeController
private readonly IMapper _mapper;
private readonly INotyfService _notyf;
public EmployeeController(IMapper mapper, INotyfService notyf)
{
_mapper = mapper;
_notyf = notyf;
}
public async Task<ActionResult> Index()
{
try
{
string emp = (HttpContext.Session.GetString("EmpID"));
string user = (HttpContext.Session.GetString("UserID"));
if (user == null || user == String.Empty || user.Trim() == "")
{
return RedirectToAction("Index", "Logout");
}
ViewBag.Nationalities = GetAllNationalityDTOs();
ViewBag.Positions = GetAllPositionDTOs();
ViewBag.RuleTypes = GetAllRuleTypeDTOs();
ViewBag.Religions = GetAllReligionDTOs();
ViewBag.Roles = GetAllRoleDTOs();
ViewBag.Genders = EnumHelperClass.GetListFromEnum(new GenderTypesEnum());
string pages = (HttpContext.Session.GetString("pages"));
var PagesList = JsonConvert.DeserializeObject<IEnumerable<ActualClaimDTO>>(pages);
string actions = (HttpContext.Session.GetString("actions"));
var actionsList = JsonConvert.DeserializeObject<IEnumerable<ActualClaimDTO>>(actions);
if (PagesList.Count() > 0)
{
var currentPage = PagesList.FirstOrDefault(c => c.Type == "Employee");
if (currentPage == null)
{
return RedirectToAction("Index", "Logout");
}
if (actionsList.Count() > 0)
{
ViewBag.currentActions = actionsList.Where(c => c.ParentID == currentPage.ID);
}
}
return await Task.FromResult(View("Views/Payoll/Employees/Employee/Index.cshtml"));
}
catch (Exception ex)
{
return BadRequest($"Error getting from api: {ex.Message},{ex.InnerException}");
}
}
public IActionResult UrlDatasource([FromBody] DataManagerRequest dm)
{
IEnumerable<EmployeeDTO> employees = BasicAPIHandler.GetList<EmployeeDTO>("Employee/GetEmployeesNotDeleted").Result;
DataOperations operation = new DataOperations();
var DataSource = _mapper.Map<IEnumerable<EmployeeViewModel>>(employees.OrderBy(c=>c.IsResigned));
if (dm.Search != null && dm.Search.Count > 0)
{
DataSource = operation.PerformSearching(DataSource, dm.Search); //Search
}
if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting
{
DataSource = operation.PerformSorting(DataSource, dm.Sorted);
}
if (dm.Where != null && dm.Where.Count > 0) //Filtering
{
DataSource = operation.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator);
}
int count = DataSource.Cast<EmployeeViewModel>().Count();
if (dm.Skip != 0)
{
DataSource = operation.PerformSkip(DataSource, dm.Skip); //Paging
}
if (dm.Take != 0)
{
DataSource = operation.PerformTake(DataSource, dm.Take);
}
var usersRolres = GetAllUserRolesDTOs();
var users = GetAllUsersDTOs();
foreach (var employee in DataSource)
{
employee.RoleID =usersRolres.FirstOrDefault(c => c.UserId == users.FirstOrDefault(c => c.EmployeeID == employee.ID).Id).RoleId;
}
return dm.RequiresCounts ? Json(new { result = DataSource, count = count }) : Json(DataSource);
}
public IActionResult EditPartial([FromBody] CRUDModel<EmployeeViewModel> value)
{
ViewBag.Nationalities = GetAllNationalityDTOs();
ViewBag.Positions = GetAllPositionDTOs();
ViewBag.RuleTypes = GetAllRuleTypeDTOs();
ViewBag.Religions = GetAllReligionDTOs();
ViewBag.Roles = GetAllRoleDTOs();
return PartialView("Views/Payoll/Employees/Employee/_DialogEditPartial.cshtml", value.Value);
}
public IActionResult AddPartial([FromBody] CRUDModel<EmployeeViewModel> value)
{
ViewBag.Nationalities = GetAllNationalityDTOs();
ViewBag.Positions = GetAllPositionDTOs();
ViewBag.RuleTypes = GetAllRuleTypeDTOs();
ViewBag.Religions = GetAllReligionDTOs();
ViewBag.Roles = GetAllRoleDTOs();
return PartialView("Views/Payoll/Employees/Employee/_DialogAddPartial.cshtml");
}
// GET: EmployeeController/Edit/5
public IActionResult ResignPartial([FromBody] CRUDModel<EmployeeViewModel> value)
{
try
{
EmployeeDTO employee = _mapper.Map<EmployeeDTO>(value.Value);
ResignEmployeeViewModel employeeViewModel = _mapper.Map<ResignEmployeeViewModel>(employee);
return PartialView("Views/Payoll/Employees/Employee/_DialogResignPartial.cshtml", employeeViewModel);
}
catch (Exception ex)
{
return BadRequest($"Error getting from api: {ex.Message},{ex.InnerException}");
}
}
public async Task<IActionResult> Create([FromBody] CRUDModel<EmployeeViewModel> employee)
{
try
{
if (ModelState.IsValid)
{
string emp = (HttpContext.Session.GetString("EmpID"));
string user = (HttpContext.Session.GetString("UserID"));
if (user == null || user == String.Empty || user.Trim() == "")
{
return RedirectToAction("Index", "Logout");
}
int empID = int.Parse(emp);
int userID = int.Parse(user);
EmployeeDTO employeeDTO = _mapper.Map<EmployeeDTO>(employee.Value);
employeeDTO.CreatedBy = userID;
employeeDTO.CreatedDateTime = DateTime.Now;
ValidationResponse validationResponse = await BasicAPIHandler.PostRecord<EmployeeDTO>("Employee/CreateEmployee", employeeDTO);
string msg = validationResponse.Message;
return await Task.FromResult(Json(new { data = employee.Value, message = msg }));
}
throw new Exception("Error in Data Fields");
}
catch (Exception ex)
{
return await Task.FromResult(Json(ex.Message + ". " + ex.InnerException.Message));
}
}
public async Task<IActionResult> Edit([FromBody] CRUDModel<EmployeeViewModel> employee)
{
try
{
if (employee.Value.ID == 0)
{
return BadRequest();
}
if (ModelState.IsValid)
{
EmployeeDTO employeeTO = _mapper.Map<EmployeeDTO>(employee.Value);
if(employeeTO.ResignDate !=null)
{
employeeTO.IsResigned = true;
}
else
{
employeeTO.IsResigned = false;
}
ValidationResponse validationResponse = await BasicAPIHandler.PutRecord<EmployeeDTO>("Employee/UpdateEmployee/" + employee.Value.ID, employeeTO);
string msg = validationResponse.Message;
return await Task.FromResult(Json(new { data = employee.Value, message = msg }));
}
return await Task.FromResult(Json(_mapper.Map<EmployeeViewModel>(employee.Value)));
}
catch (Exception ex)
{
return await Task.FromResult(Json(ex.Message + ". " + ex.InnerException.Message));
}
}
public async Task<IActionResult> Delete([FromBody] CRUDModel<EmployeeViewModel> employee)
{
try
{
int id = int.Parse(employee.Key.ToString());
if (employee.Key == null && id == 0)
{
return BadRequest();
}
ValidationResponse validationResponse = await BasicAPIHandler.DeleteRecord<EmployeeDTO>("Employee/DeleteEmployee/" + id); ;
if (validationResponse.Response)
{
ViewBag.IsValid = "True";
}
string msg = validationResponse.Message;
return await Task.FromResult(Json(new { data = employee.Value, message = msg }));
}
catch (Exception ex)
{
return await Task.FromResult(Json(ex.Message + ". " + ex.InnerException.Message));
}
}
public async Task<IActionResult> Resign([FromBody] CRUDModel<ResignEmployeeViewModel> employee)
{
try
{
if (employee.Value.ID == 0)
{
return BadRequest();
}
if (ModelState.IsValid)
{
EmployeeDTO employeeDTO = await BasicAPIHandler.GetRecord<EmployeeDTO>("Employee/GetEmployee/" + employee.Value.ID);
employeeDTO.IsResigned = true;
employeeDTO.ResignDate = employee.Value.ResignDate;
ValidationResponse validationResponse = await BasicAPIHandler.PutRecord<EmployeeDTO>("Employee/UpdateEmployee/" + employee.Value.ID, employeeDTO);
string msg = validationResponse.Message;
return await Task.FromResult(Json(new { data = employee.Value, message = msg }));
}
return await Task.FromResult(Json(_mapper.Map<EmployeeViewModel>(employee.Value)));
}
catch (Exception ex)
{
return await Task.FromResult(Json(ex.Message + ". " + ex.InnerException.Message));
}
}
}
Thanks for All
In Edit Partial View
@model AssembleWeb.ViewModel.Payroll.Employees.EmployeeViewModel
@*//define the model for store the model values*@
@using Syncfusion.EJ2
<div>
<div class="form-row">
<div class="form-group col-md-12">
<div class="e-float-input e-control-wrapper">
<input asp-for="ID" type='number' [email protected] disabled />
<span class="e-float-line"></span>
<label asp-for="ID" class="e-float-text e-label-top text-dark">ID</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="FullName" type="text" [email protected] />
<span class="e-float-line"></span>
<label asp-for="FullName" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="AliasName" type="text" [email protected] />
<span class="e-float-line"></span>
<label asp-for="AliasName" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="AliasName" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="Email" type="email" [email protected] />
<span class="e-float-line"></span>
<label asp-for="Email" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="EmpCode" type="text" [email protected] />
<span class="e-float-line"></span>
<label asp-for="EmpCode" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="EmpCode" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="NationalID" type="text" [email protected] maxlength="14" />
<span class="e-float-line"></span>
<label asp-for="NationalID" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="NationalID" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="PPNumber" type="text" [email protected] />
<span class="e-float-line"></span>
<label asp-for="PPNumber" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="PPNumber" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="GSalary" type="number" min="0" [email protected] />
<span class="e-float-line"></span>
<label asp-for="GSalary" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="GSalary" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="NSalary" type="number" min="0" [email protected] />
<span class="e-float-line"></span>
<label asp-for="NSalary" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="NSalary" class="text-danger"></span>
</div>
</div>
</div>
</div>
<ejs-scripts></ejs-scripts>
In Custom Edit Partial View
@model AssembleWeb.ViewModel.Payroll.Employees.ResignEmployeeViewModel
@*//define the model for store the model values*@
@using Syncfusion.EJ2
<div>
<div class="form-row">
<div class="form-group col-md-12">
<div class="e-float-input e-control-wrapper">
<input asp-for="ID" type='text' hidden="hidden" [email protected] />
<span class="e-float-line"></span>
<label asp-for="ID" hidden="hidden" class="e-float-text e-label-top text-dark">ID</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="FullName" type="text" [email protected] disabled/>
<span class="e-float-line"></span>
<label asp-for="FullName" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
</div>
<div class="form-group col-lg-6">
<div class="e-float-input e-control-wrapper">
<input asp-for="AliasName" type="text" [email protected] disabled/>
<span class="e-float-line"></span>
<label asp-for="AliasName" class="e-float-text e-label-top text-dark"></label>
<span asp-validation-for="AliasName" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-lg-12">
<div class="e-float-input e-control-wrapper">
<label asp-for="ResignDate" class="text-dark"></label>
<ejs-datepicker id="ResignDate" ejs-for="ResignDate" [email protected] format="dd-MM-yyyy"></ejs-datepicker>
<span class="e-float-line"></span>
<span asp-validation-for="ResignDate" class="text-danger"></span>
</div>
</div>
</div>
</div>
<ejs-scripts></ejs-scripts>
- Share the screenshot or video demonstration of your requirement.
- Explain the more details on the custom edit behavior which you want to achieve in your Grid application.
- Do you want to render a new dialog with some selected input fields for custom edit?
- Are you using the fields that are available in the Grid component for custom edit?
- Do you want to use our Insert, Update and Delete methods for custom edit?
- 4 Replies
- 3 Participants
-
AH Ahmed
- Sep 13, 2021 09:15 AM UTC
- Sep 15, 2021 01:42 PM UTC