How to send parameters to Html.Kendo().Dialog()? - asp.net-mvc

I need to send a parameter to Html.Kendo().Dialog():
var diff = Num1 = Num2;
var msg = "The amiunt of " + diff + " will be subtracted"
#(Html.Kendo().Dialog()
.Title("Update")
.Content("<p>" + msg + <p>")
However, that construct does not allow this, saying that "msg" does not exist in the current content
How can I do that?
Updated version:
if ((Math.abs(newAmount) < Math.abs(Amount)) && newAmount != 0) {
$("#dialog").kendoDialog({
width: "400px",
title: "Split Ticket Confirmation",
closable: true,
modal: true,
content: "<div style='text-align: center'>" + msg + "</div>",
actions: [
{
text: 'OK',
action: function (e) {
$('.modal-content').html('');
$('#modal-container').modal('hide');
SaveData();
},
primary: true
},
{
text: "CANCEL",
action: function (e) {
$('.modal-content').html('');
$('#modal-container').modal('hide');
return false;
},
primary: true
}
]
}).data("kendoDialog").open();
}
else {
SaveData();
}

Using Razor HTML C# syntax, you can achieve it without errors by doing this:
#{
var msg = "The amiunt of " + diff + " will be subtracted";
}
Then just passing it regularly to the Content as you already did.
If you are using JavaScript and really want to use that dialog inside script tags then you can do this:
var dialog = $('#dialog'), undo = $("#undo");
undo.click(function () {
dialog.data("kendoDialog").open();
undo.fadeOut();
});
function onClose() {
undo.fadeIn();
}
var diff = Num1 = Num2;
var msg = "The amiunt of " + diff + " will be subtracted";
dialog.kendoDialog({
width: "400px",
title: "Update",
closable: false,
modal: false,
content: "<p>" + msg + "<p>",
actions: [
{
text: "OK",
action: function(e){
// e.sender is a reference to the dialog widget object
// OK action was clicked
// Returning false will prevent the closing of the dialog
return false;
},
primary: true
},
{ text: 'Action 2' },
{ text: 'Action 3', primary: true }
],
close: onClose
});
To add another action per request, to the Html.Kendo.Dialog() construct you can do the following:
#Html.Kendo.Dialog()
.Actions(actions =>
{
actions.Add().Text("Ok").Action("onOkClick").Primary(true);
})
And inside your your script tag you create the JS method:
function onOkClick(e)
{
//Do something
}

What I am doing is writing a partial into the page on the event that opens the dialog:
function OpenDialog() {
$.ajax({
url: '#Url.Action("ItemSearch", "Invoice")',
data: {
PartNumber: dataItem.Id,
AltPartNumber: 1,
Description: 1,
Application: 1
},
success: function (result) {
$("#SearchDialogContainer").html(result);
},
error: function (result) {
alert("An error occurred.");
}
});
}
<div id="SearchDialogContainer"></div>
And in the partial:
#model ParameterModel
#(Html.Kendo().Dialog()
.Name("SearchDialog")
.Title("Choose An Item To Add")
.Content("<div class='k-textbox k-space-right search-wrapper'><input id='employees-search' type='text' placeholder='Search employees' value='#Model.Property'/></div>")
.Width(400)
.Modal(true)
.Visible(false)
.Actions(actions =>
{
actions.Add().Text("Add Item").Primary(true);
actions.Add().Text("Cancel");
})
)
<script>
$(document).ready(function () {
$('#SearchDialog').data("kendoDialog").open();
});
</script>

Related

Set value of ng-select2 on a button click

The scenario is, I need to set the value of the dropdown (ng-select2) when a user presses on edit button present on the page. I am using ajax to fetch the options. The code is in angular.
I took reference from : https://github.com/tealpartners/ng-select2
<div class="form-div">
<label for="uploader">Select Uploader<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="uploader" id="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
<div class="form-div">
<label for="uploader">Select Approver<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="approver" [id]="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
</div>
setSelect2Options() {
this.select2Options = {
triggerChange: true,
allowClear: true,
placeholder : 'Select User* ',
minimumInputLength: 3,
ajax: {
url: '/api/reward/uploader/approver/search/user?limit=15',
headers: {
'X-XSRF-TOKEN': sessionStorage.getItem("auth"),
'content-type': 'application/json'
},
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term, page) {
return {
q: term.term, // search term
_: term._type
};
},
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
id: item.id,
text: item.name + " - " + item.email
}
})
};
}
},
//[placeholder]="'Select User* '"
}
}
The above codes are well and good. But now on a button click i need to set a value inn the select box.
this.vcDataService.getUploaderAproverDetails(id).subscribe((res: any) => {
this.uploaderApproverForm.controls['approver'].setValue(res.approverDetails.uploaderUserId);
this.uploaderApproverForm.controls['uploader'].setValue(res.uploaderDetails.approverUserId);
console.log("134", res)//uploaderUserId
//this.select2Options.ajax.processResults.push({id: 103, text: "aa"})
this.select2Options.placeholder="aa";
//this.displayUploader = "aaa";
// $('#uploader').val('ENABLED_FROM_JS');
// $('#uploader').trigger('change');
// this.select2Options.templateSelection = {
// selected: true,
// id: res.approverDetails.approverUserId,
// text: res.approverDetails.approverName,
// title: res.approverDetails.approverName
// }
// this.select2Options.initSelection = {
// callback: {
// data: {"id":103, "text":'ENABLED_FROM_JS'}
// }
// }
console.log(this.select2Options);
this.updateApproverUploader = true;
this.uploaderApproverId = res.uploaderApproverId;
this.cd.detectChanges();
},
err => {
Swal.fire('Oops...', err.error.err, 'error');
})
I tried few things but didn't got the workaround.
After going through the documentation I found a solution for it. I used the data attribute of the ng-select2 and assigned it to a Select2OptionData type variable.
import { Select2OptionData} from 'ng-select2';
patch_panel_array: Select2OptionData[];
Then I added the required data which I needed to show in the field as displayed below:
res.panelApprovers.map(item => {
this.patch_panel_array.push({
id: item.panelApproverUserId,
text: item.panelApproverUserName + " - " + item.panelApproverUserEmail
})
approverIds.push(String(item.panelApproverUserId));
});
this.formData.controls['panelApprover'].setValue(approverIds);
And here is my select 2 field:
<ng-select2 formControlName="panelApprover" [data]="patch_panel_array" [options]="select2OptionsPanel" width="100%" style="width: 100%;">
</ng-select2>

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "DescripciĆ³n" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

Using unescaped '#' characters on Ag Grid Enterprise React on Context Menu

When I am using the Ag-Grid context menu on application, I get a message on console saying:
[Deprecation] Using unescaped '#' characters in a data URI body is deprecated and will be removed in M68, around July 2018. Please use '%23' instead. See https://www.chromestatus.com/features/5656049583390720 for more details.
I really don't get any error, but I'm afraid on the message. Can any one update any thing about this message?
This is the component that use this.sate.columnDefs with renderframework like that:
<AgGridReact
// properties
columnDefs={this.state.columnDefs}
rowData={consumers.items}
animateRows
enableColResize
enableSorting={true}
rowSelection="single"
suppressMenuHide={true}
enableFilter={true}
onCellClicked={this.onCellClicked.bind(this)}
onGridReady={this.state.onGridReady}
paginationPageSize={10}
pagination={true}
multiSortKey="ctrl"
getContextMenuItems={this.state.getContextMenuItems}
/>
columnDefs: [
{
headerName: "",
suppressFilter: true,
width: 30,
cellRendererFramework: function (params) {
if (params.data.permissions.length > 0) {
return <i className="fa fa-ellipsis-v" />;
}
}
},
{
headerName: language.LAST_NAME,
field: "person.last_name",
enableRowGroup: true,
filter: "agSetColumnFilter",
},
{
headerName: language.FIRST_NAME,
field: "person.first_name",
enableRowGroup: true,
filter: "agSetColumnFilter",
}
],
sortingOrder: ["desc", "asc", null],
getContextMenuItems: this.getContextMenuItems.bind(this),
onGridReady: function (params) {
var sort = [
{
colId: "person.last_name",
sort: "asc"
},
{
colId: "person.first_name",
sort: "asc"
},
{
colId: "medical_id",
sort: "asc"
},
{
colId: "person.date_of_birth",
sort: "asc"
}
];
this.gridApi = params.api;
this.gridApi.setSortModel(sort);
params.api.sizeColumnsToFit();
}
getContextMenuItems(params) {
let language = languageActions.getLanguage();
const { props } = this;
this.setState({
showActionDiv: false
});
var aResult = [];
params.node.data.permissions.map((permision, index) => {
let language = languageActions.getLanguage();
switch (permision) {
case "Update":
aResult.push(
{
name: language.VIEW_DETAIL,
icon: '<span class="fa fa-edit icon-ag-grid"></span>',
action: () => {
//console.log(this.props);
this.props.toggleShowProfile();
}
}
);
break;
case "Read":
aResult.push(
{
name: language.VIEW_SCHEDULE,
icon: '<span class="fa fa-calendar icon-ag-grid"></span>',
action: () => {
this.props.toggleShowScheduledServices();
}
}
);
break;
}
});
aResult.push(
"separator",
"copy",
"csvExport",
"excelExport",
"autoSizeAll");
return aResult;
}

Kendo grid footer template sum issue

var dataSourceDashboard = new kendo.data.DataSource({
pageSize: 20,
type: "json",
transport: {
read: function (operation) {
if (navigator.onLine) {
$.ajax({
url: '/Home/Dashboard_Read/',
type: "GET",
dataType: "json",
success: function (response) {
try
{
localStorage.setItem("Dashboard_Read", JSON.stringify(response));
}
catch (domException)
{
if (domException.name === 'QuotaExceededError' ||
domException.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
// Fallback code comes here.
$("#progressMsgError").html("Cannot save the data for offline use, please clear the cache, or call administrator!");
$('#myModalError').modal('show');
}
}
operation.success(response);
BindSitesCombo(response);
//// initial sync of data
//var cashedDataBaseJson = [];
//var cashedDataBase = localStorage.getItem("cashedDataBase");
//if (cashedDataBase != null || cashedDataBase != undefined) {
// cashedDataBaseJson = JSON.parse(cashedDataBase);
// if (cashedDataBaseJson.length > 0) {
// syncInitialData(cashedDataBaseJson);
// localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
// }
//}
//else
//{
// syncInitialData(response);
// localStorage.setItem("cashedDataBase", JSON.stringify(response));
//}
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase == null || cashedDataBase == undefined) {
localStorage.setItem("cashedDataBase", JSON.stringify(response));
}
else {
var cashedDataBaseJson = [];
var cashedDataBase = localStorage.getItem("cashedDataBase");
if (cashedDataBase != null || cashedDataBase != undefined) {
cashedDataBaseJson = JSON.parse(cashedDataBase);
var i = response.length;
while (i--)
{
var ifsiteisinthelist = contains(cashedDataBaseJson, response[i]);
if (ifsiteisinthelist == false)
{
cashedDataBaseJson.push(response[i]);
}
}
localStorage.setItem("cashedDataBase", JSON.stringify(cashedDataBaseJson));
}
}
rempvesyncedlinks();
},
error: function (response)
{
window.location.href = "/account/login";
}
});
}
else {
var cashedData = localStorage.getItem("Dashboard_Read");
if (cashedData != null || cashedData != undefined) {
//if local data exists load from it
var data = JSON.parse(cashedData);
operation.success(data);
BindSitesCombo(data);
rempvesyncedlinks();
}
}
}
},
schema: {
model: {
id: "SiteID",
}
},
//change: function (e) {
// $.each(dataSourceDashboard.data(), function (index, value) {
// $('#cmbAllSites')
// .append($("<option></option>")
// .attr("value", value.SiteID)
// .text(value.SiteName));
// });
//}
change: function (e) {
rempvesyncedlinks();
},
aggregate: [
{ field: "DailyTotalFormated", aggregate: "sum" },
{ field: "WeeklyTotalFormated", aggregate: "sum" },
{ field: "WeeklySiteTotalFormated", aggregate: "sum" },
{ field: "WeeklyGoal", aggregate: "sum" }
],
});
$(function () {
$("#gridDashboard").kendoGrid({
dataSource: dataSourceDashboard,
filterable: false,
groupable: false,
toolbar: false,
pageable: {
change: function (e) {
rempvesyncedlinks();
}
},
sortable: true,
height: 600,
columns: [
{ field: "SiteName", title: "MY COMPANIES", template: '#=SiteName#',footerTemplate: "Total " },
{ field: "DailyTotalFormated", title: "MY DAILY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyTotalFormated", title: "MY WEEKLY TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklySiteTotalFormated", title: "WEEKLY SITE TOTAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "WeeklyGoal", title: "WEEKLY SITE GOAL", aggregates: ["sum"], footerTemplate: "#=sum#" },
{ field: "", title: "SYNC", template: "# if (isSynced == true) { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/ready.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Ready</div></div>" +
"# } else { #" +
"<div style='width: 130px;margin: auto;'><img src='/images/pleasesync.png' alt='Up-to-date' /><div style='font-size:15px; font-weight:bolder; float: right;'>Please Sync</div></div>" +
"# } # <a id='syncforoffline#=SiteID#' href='##' onclick='syncDataForSite(#=SiteID#);return false;'>Sync for offline</a>"
},
{ field: "SiteLogo", title: " ", hidden : true },
],
editable: false
});
$("#cmbAllSites").change(function ()
{
var di = dataSourceDashboard.data()[this.selectedIndex - 1];
setSiteID(di.SiteID, di.SiteLogo, di.SiteName);
});
});
Footer sum is not calculated
What is wrong in this code, why does the total show last row by default?
I fixed the issue. I am just adding:
model: {
id: "SiteID",
fields: {
SiteName: { type: "string" },
DailyTotalFormated: { type: "number" },
WeeklyTotalFormated: { type: "number" },
WeeklySiteTotalFormated: { type: "number" },
WeeklyGoal: { type: "number" }
}
}

Keep impromptu "up" while performing a jquery Ajax/MVC post

Is there a way to keep the impromptu dialog box displayed during a post?
Here's the javascript code
$('#linkPostTest').click(function() {
openprompt();
});
function openprompt() {
var temp = {
state0: {
html: 'Are you sure you want to post?<br />',
buttons: { Yes: true, No: false },
focus: 1,
submit: function(v, m, f) {
if (v) {
var form = $('frmPostTest');
$.ajax(
{
type: 'POST',
url: '/Path/TestPost',
data: form.serialize(),
success: function(data) {
// I realize I could check "data"
// for true...just have not
// implemented that yet....
$.prompt.goToState('state1');
//$.prompt('Test was successful!');
},
error: function() {
$.prompt.goToState('state2');
//$.prompt('Test was not successful.');
}
}
);
return true;
}
else {
//$.prompt.goToState('state1'); //go forward
return false;
}
}
},
state1: {
html: 'Test was successful!',
buttons: { Close: 0 },
focus: 0,
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
},
state2: {
html: 'Test was not successful.<br />',
buttons: { Close: 0 },
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
}
};
$.prompt(temp);
}
The controller does this
[AcceptVerbs(HttpVerbs.Post)]
public bool TestPost()
{
// runs some code that saves some data...
// this works fine
bool updated = functionThatSavesCode();
return updated;
}
After I click Yes when the 'Are you sure you want to post?' impromptu dialog is displayed... it disappears...How can I make it stay displayed?
OK got it to work...I'm really impressed with the impromptu plug-in and jQuery!
Two of the things I did differently to get this to work was to add the two
return false;
statements under the state0 block and...
to set the the ajax call to
async: false,
Here's the new javascript:
$('#linkTestPost').click(function() {
TestPost();
});
function TestPost() {
var temp = {
state0: {
html: 'Are you sure you want to post?<br />',
buttons: { Yes: true, No: false },
focus: 1,
submit: function(v, m, f) {
if (v) {
if (PostView() === true) {
$.prompt.goToState('state1');
// the line below was missing from my original attempt
return false;
}
else {
$.prompt.goToState('state2');
// the line below was missing from my original attempt
return false;
}
}
else {
return false;
}
}
},
state1: {
html: 'Test Post was successful!',
buttons: { Close: 0 },
focus: 0,
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
},
state2: {
html: 'Test Post was not successful',
buttons: { Close: 0 },
submit: function(v, m, f) {
if (v === 0) {
$.prompt.close();
}
}
}
};
$.prompt(temp);
}
function PostView() {
var form = $('frmTestPost');
var postSuccess = new Boolean();
$.ajax(
{
type: 'POST',
url: '/Path/TestPost',
data: form.serialize(),
// the line below was missing from my original attempt
async: false,
success: function(data) {
postSuccess = true;
},
error: function() {
postSuccess = false;
}
});
return postSuccess;
}

Resources