Skip to content

Instantly share code, notes, and snippets.

@joshi-kumar
Created February 17, 2018 11:43
Show Gist options
  • Save joshi-kumar/206aefbcafbabc539a3e1a3c213925c7 to your computer and use it in GitHub Desktop.
Save joshi-kumar/206aefbcafbabc539a3e1a3c213925c7 to your computer and use it in GitHub Desktop.
Add data into kendo grid using ajax
@model EmailAndNotificationModel
@using System.Globalization;
@{
var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;
//page title
ViewBag.Title = "Send email & notification";
var GroupRolesIdsInput = new List<int>();
}
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
@*<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>*@
<script type="text/javascript" src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" type="text/css" />
@using (Html.BeginForm()) //"SendCustomerEmailAndNotification", "Customer", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
var tempUserIds = 0;
<div class="content-header clearfix">
<h1 class="pull-left">
Send email and notification
</h1>
<div class="pull-right">
<button type="button" onclick="sendMessage();" name="save" id="sendButton" class="btn btn-default"><i class="fa fa-floppy-o"></i> Send </button>
@*<button type="submit" name="save" class="btn btn-default" id="Submit" value="submit">
<i class="fa fa-floppy-o"></i> Send
</button>*@
</div>
</div>
<div class="content">
<div class="form-horizontal">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<div class="col-md-2">
@Html.NopLabelFor(model => model.SelectedGroupRoleIds)
</div>
<div class="col-md-9" id="customersRole">
<div class="input-group input-group-required" id="selectedGroup">
@Html.EditorFor(model => model.SelectedGroupRoleIds, new { SelectList = Model.AvailableGroups })
<div class="input-group-btn" id="customersList">
@Html.RequiredHint()
</div>
</div>
<script>
$(document).ready(function () {
GroupRolesIdsInput = $('#@Html.FieldIdFor(model => model.SelectedGroupRoleIds)').data("kendoMultiSelect");
GroupRolesIdsInput.setOptions({
GroupRolesIdsInput: false
});
@if (Model.AvailableGroups.Count == 0)
{
<text>
GroupRolesIdsInput.setOptions({
enable: false,
placeholder: '@T("Admin.Customers.Customers.Fields.CustomerRoles.NoRoles")'
});
GroupRolesIdsInput._placeholder();
GroupRolesIdsInput._enable();
</text>
}
});
</script>
</div>
</div>
<div id="administrator" class="form-group" width:100%; height:auto; border-color:#e6e6e6; border-style:double;">
<div class="col-md-9" style="width:100%; float:left;">
<div class="content">
<div class="form-horizontal">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<div id="admincustomers-grid"></div>
<script>
$(document).ready(function () {
$("#admincustomers-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "@Html.Raw(Url.Action("FilteredGroupList", "Customer"))",
type: "POST",
dataType: "json",
data: addAntiForgeryToken
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: @(defaultGridPageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [@(gridPageSizes)],
@Html.Partial("_GridPagerMessages")
},
scrollable: false,
dataBound: onDataBound,
columns: [{
field: "Id",
headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
headerAttributes: { style: "text-align:center" },
attributes: { style: "text-align:center" },
template: "<input type='checkbox' value='#=Id#' name='#=Id#' class='checkboxGroups' id='UserId' />",
width: 30
}, {
field: "FullName",
title: "@T("Admin.Customers.Customers.Fields.FullName")",
width: 175
}]
});
});
</script>
<script type="text/javascript">
var selectedIds = [];
$(document).ready(function () {
//search button
$('#search-customers').click(function () {
var grid = $('#admincustomers-grid').data('kendoGrid');
grid.dataSource.page(1); //new search. Set page size to 1
//grid.dataSource.read(); we already loaded the grid above using "page" function
//clear selected checkboxes
$('.checkboxGroups').attr('checked', false).change();
selectedIds = [];
return false;
});
if (event.keyCode === 13) {
$("#search-customers").click();
return false;
}
$('#mastercheckbox').click(function () {
$('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
});
//find checked (checkboxes).
$('#admincustomers-grid').on('change', 'input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]', function (e) {
var $check = $(this);
if ($check.is(":checked") == true) {
var checked = jQuery.inArray($check.val(), selectedIds);
if (checked == -1) {
//add id to selectedIds.
selectedIds.push($check.val());
}
} else {
var checked = jQuery.inArray($check.val(), selectedIds);
if (checked > -1) {
//remove id from selectedIds.
selectedIds = $.grep(selectedIds, function (item, index) {
return item != $check.val();
});
}
}
updateMasterCheckbox();
});
});
function onDataBound(e) {
$('#admincustomers-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').each(function () {
var currentId = $(this).val();
var checked = jQuery.inArray(currentId, selectedIds);
//set checked based on if current checkbox's value is in selectedIds.
$(this).attr('checked', checked > -1);
});
updateMasterCheckbox();
}
function onDataBound(e) {
$('#queuedEmails-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').each(function () {
var currentId = $(this).val();
var checked = jQuery.inArray(currentId, selectedIds);
//set checked based on if current checkbox's value is in selectedIds.
$(this).attr('checked', checked > -1);
});
updateMasterCheckbox();
}
function updateMasterCheckbox() {
var numChkBoxes = $('#admincustomers-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').length;
var numChkBoxesChecked = $('#admincustomers-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]:checked').length;
$('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
}
function additionalData() {
var data = {
};
addAntiForgeryToken(data);
return data;
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
@Html.NopLabelFor(model => model.MessageForPush)
</div>
<div class="col-md-9">
@*<input type="text" id="pushmessage" class="col-md-9" style="height:100px; width:100%;"/>*@
<textarea name="pmessage" id="pushmessage" rows="3" cols="100" style="width:100%;"> </textarea>
@Html.ValidationMessageFor(model => model.MessageForPush)
@*@Html.ValidationMessageFor(model => model.MessageForPush)*@
</div>
<span class="required"> * </span>
</div>
<div class="form-group">
<div class="col-md-2">
@Html.NopLabelFor(model => model.MessageForEmail)
</div>
<div class="col-md-9" id="message">
@Html.EditorFor(model => model.MessageForEmail, "RichEditor", new { @id = "message" })
@Html.RequiredHint()
</div>
@Html.ValidationMessageFor(model => model.MessageForEmail)
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var selectedUserIds = [];
//debugger;
$('#admincustomers-grid').on('change', 'input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]', function(e) {
var $check = $(this);
if ($check.is(":checked") == true) {
var checked = jQuery.inArray($check.val(), selectedUserIds);
if (checked == -1) {
//add id to selectedUserIds.
selectedUserIds.push($check.val());
}
} else {
var checked = jQuery.inArray($check.val(), selectedUserIds);
if (checked > -1) {
//remove id from selectedUserIds.
selectedUserIds = $.grep(selectedUserIds, function(item, index) {
return item != $check.val();
});
}
}
//updateMasterCheckbox();
});
//click on send button it execute.
function sendMessage() {
//debugger;
selectedUserIds = [];
var gridData = $('#admincustomers-grid').data('kendoGrid')._data;
var selectedUserIds = '';
var isSelected = false;
$('input:checkbox.checkboxGroups').each(function () {
var UId = $(this).attr('name');
//var UId2 = $("#UserId").is(':checked');
if (this.checked) { if (selectedUserIds == '') { selectedUserIds = UId } else { selectedUserIds += "," + UId } }
});
//Get Push Message Content.
var pushMessage = $('#pushmessage').val();
// Get Rich text Editor Content.
tinyMCE.triggerSave();
var messageContent = window.parent.tinymce.get('MessageForEmail').getContent();
//bind all parameter (action's)
var postData = {
selectedUserIds: selectedUserIds,
pushMessage: pushMessage,
messageContent: messageContent
};
addAntiForgeryToken(postData);
$.ajax({
type:'POST',
url: '@Url.Action("SendToCustomerEmailAndNotification", "Customer")',
data: postData, //{ selectedUserIds: selectedUserIds, messageContent: messageContent },
success: function (data) {
debugger;
alert("email & notification sent successfully.")
},
error: function (xhr, ajaxOptions, thrownError) {
debugger;
alert("please fill all required (*) fields.")
//alert(thrownError);
},
});
}
//end send button.
</script>
}
<script type="text/javascript">
var selectedGroupIds = [];
$(document).ready(function () {
debugger;
$('#SelectedGroupIds').multiselect({
includeSelectAllOption: true,
maxHeight: 200
});
$('#selectedGroup').change(function () {
//e.preventDefault();
selectedGroupIds.length = 0;
var gridData = $('#admincustomers-grid').data('kendoGrid')._data;
var selectedUsersId = $("#admincustomers-grid input[type=checkbox][name='UserId']:checked").val()
var selectedUsersIds = [];
$("#admincustomers-grid input[type=checkbox][name='UserId']").map(function () {
selectedUsersIds.push($(this).val());
});
var finalselectedUsersIds = [];
finalselectedUsersIds = selectedUsersIds.toString();
var customerRolesValues = GroupRolesIdsInput.dataSource;
var roleLength = GroupRolesIdsInput._values.length;
if(roleLength > 0)
{
for (i = 0; i < roleLength; i++) {
var administrators = false; var registered = false; var authors = false;
var value = GroupRolesIdsInput._dataItems[i].text;
var selectedGroupId = GroupRolesIdsInput._dataItems[i].value;
$.each(GroupRolesIdsInput._dataItems, function (i, item) {
selectedGroupIds.push(item.value);
});
}
var postData = {
selectedGroupIds: selectedGroupIds
};
addAntiForgeryToken(postData);
$.ajax({
type: "POST",
url: "@(Url.Action("FilteredGroupList", "Customer"))",
dataType: 'json',
data: postData,
success: function (data) {
debugger;
//alert(data.Total);
if( data.Total > 0)
{
//$("#admincustomers-grid").data("kendoGrid").dataSource.data([{"Id":1, "Id":1,"FullName":"AAA"}]);
$("#admincustomers-grid").data("kendoGrid").dataSource.data(JSON.parse(data.Data));
// $("#admincustomers-grid").data("kendoGrid").dataSource.data([{"Id":133753,"FullName":"New Author"},{"Id":132749,"FullName":"Aman Mishra"},{"Id":132743,"FullName":"mahesh kumar"},{"Id":131647,"FullName":"Joshi kumar"},{"Id":131624,"FullName":"Vikas Verma"},{"Id":131523,"FullName":"Ravi Shakti"},{"Id":130350,"FullName":"Saurav Kr"},{"Id":54541,"FullName":"Ashish Pandey"}]);
//$('#administrator').show();
//var grid = $("#admincustomers-grid").data("kendoGrid");
//var dataSource = new kendo.data.DataSource({ data: result });
////grid.setDataSource(dataSource);
//grid.dataSource.read();
//var grid = $('#admincustomers-grid').data('kendoGrid');
//var dataSource = new kendo.data.DataSource({ data: result });
////var dataSource1 = new keno.data.DataSource({_data:result});
//grid.setDataSource(dataSource);
//grid.dataSource.read();
//$("#admincustomers-grid").data("kendoGrid").dataSource._data(data);
//var grid = $('#admincustomers-grid').data('kendoGrid').refresh;
//var grid1 = $('#admincustomers-grid').data('kendoGrid').data;
//var grid2 = $('#admincustomers-grid').data('kendoGrid')._data;
//grid.dataSource.page(1);
}
else
{
alert("no any user exist in selected group.")
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
}
else {
//$('#administrator').hide();
}
//return false;
});
});
</script>
@* =======================================================================================
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="content-header clearfix">
<h1 class="pull-left">
Send email and notification
</h1>
<div class="pull-right">
<button type="submit" name="save" class="btn btn-default" id="Submit" value="submit">
<i class="fa fa-floppy-o"></i> Send
</button>
</div>
</div>
var validationSummary = Html.ValidationSummary(true);
if (!MvcHtmlString.IsNullOrEmpty(validationSummary))
{
<div class="message-error">@validationSummary</div>
}
if (TempData["error"] != null)
{
<span style="margin-left:108px;">@TempData["error"]</span>
}
if (ViewBag.SuccessMessageKey == 1)
{
<span style="margin-left:108px; color:green">@ViewBag.SuccessMessage</span>
}
<div class="content">
<div class="form-horizontal">
<div class="panel-group">
@if (ViewBag.MessageEmpty != null)
{
<div style="background-color:#ff8b8b; color:#000000; height:50px; width:100%;">
<ul> <li> @ViewBag.MessageEmpty </li></ul>
</div>
}
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<div class="col-md-2">
@Html.NopLabelFor(model => model.SelectedCustomerIds)
</div>
<div class="col-md-9">
@Html.DropDownList("SelectedCustomerIds", Model.AvailableUser, new { @multiple = "true" })
@Html.RequiredHint()
@Html.ValidationMessageFor(model => model.SelectedCustomerIds)
</div>
</div>
<div class="form-group">
<div class="col-md-2">
@Html.NopLabelFor(model => model.Message)
</div>
<div class="col-md-9">
@Html.EditorFor(model => model.Message, "RichEditor", new { @id = "message" })
@Html.ValidationMessageFor(model => model.Message)
@Html.RequiredHint()
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
<script>
$(document).ready(function () {
debugger;
//$('CustomerId').multipleSelect();
$('#SelectedCustomerIds').multiselect({
includeSelectAllOption: true,
maxHeight: 200
});
})
</script>*@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment