How to pass object from kendo grid to kendo window in MVC - model-view-controller

How can I pass the Object of the selected row from the grid to window on button click event of the grid
.
<script>
function editItem(e) {
e.preventDefault();
var selectedObj= this.dataItem($(e.currentTarget).closest("tr"));
//selectedObj is object selected by user
var myWin = $("#windowstatus").kendoWindow({
width: "450px",
height: "250px",
title: "Some Title",
content: {
url: "../SomeURL", //controller name
data: { selectedObj } //passing obj to mvc controller
}
});
myWin.data("kendoWindow").open();
return false;
}
</script>
My ActionResult
public class XXX: Controller
{
public ActionResult Index(MyClass obj)
{
// Do Something
}
}
I cant recive the object in mvc controller and always be null

var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
if (selectedItem != null && selectedItem != "" && selectedItem != undefined)
{
var wOptions =
{
content: "/xx/XxController/Index/" + selectedItem.Id//
If you have the parameter,
iframe: true,
modal: true,
width: "50%",
height: "90%",
close: function () {
this.destroy();
$('body').addClass('non-overflow');
},
open: function () {
this.center();
}
};
var windowParent = windowParent == undefined ? "list-splitter" : windowParent;
$("#" + windowParent).append("<div id='printWindow'> </div>")
$("#printWindow").kendoWindow(wOptions);
}
The following code block also calls the window js method
window: function (url, params, windowParent) {
var wOptions = {
content: url + "/?frameFilter=" + params,
iframe: true,
modal: true,
width: "90%",
height: "90%",
close: function () {
this.destroy();
$('body').addClass('non-overflow');
},
open: function () {
this.center();
}
};
windowParent = windowParent == undefined ? "pop-splitter" : windowParent;
$("#" + windowParent).append("<div id='popupWindow'> </div>")
$("#popupWindow").kendoWindow(wOptions);
},
I hope it helps

Related

Summernote custom button with dialog

I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));

knockout validation for array of objects

I have an array of dynamically added objects and I want to validate this array for required fields and numeric values.
I have 3 buttons, one for adding note, another for removing note and one for saving
How to validate every object ?
.. the code:
$(function () {
var initialData = [{
Title: "",
NoteText: "",
Suggestion: "",
MediaTime: ""
}];
var CreateNewNoteModel = function (Notes) {
var self = this;
self.Notes = ko.observableArray(ko.utils.arrayMap(Notes, function (Note) {
return { Title: Note.Title, NoteText: Note.NoteText, Suggestion: Note.Suggestion, MediaTime: Note.MediaTime };};
}));
var i = 1;
self.addNote = function () {
self.Notes.push({
Title: "", NoteText: "", Suggestion: "", MediaTime: ""
});
$('#editor' + i).wysihtml5();
$('#editorB' + i).wysihtml5();
i++;
};
self.removeNote = function (Note) {
self.Notes.remove(Note);
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Notes), null, 2));
var jsondata = self.lastSavedJson();
$.ajax({
url: "/api/Notes/?mid=" + m + "&p=" + p,
cache: false,
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: jsondata,
success: function () {
alert("Success");
document.location.reload(true);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new CreateNewNoteModel(initialData));
});
I am using jQuery validate plugin to add validation to knockout-js by using jQuery's validation methods: "$.validator.addMethod" and "$.validator.addClassRules".
Example:
First define your validation methods and css classes. Later on, we add the css classes to your inputs to validate your fields.
function DefineValidationRules() {
$.validator.addMethod("validateNumber", ValidateInteger, "This field is not a number");
$.validator.addMethod("validateRequired", $.validator.methods.required, "This field is required");
$.validator.addMethod("validateMin", $.validator.methods.min, $.format("This number be greater than or equal to {0}"));
$.validator.addMethod("validateMax", $.validator.methods.min, $.format("This number must be less than or equal to {0}"));
$.validator.addMethod("validateMinlength", $.validator.methods.minlength, $.format("This field must contain at least {0} characters"));
$.validator.addMethod("validateRangelength", $.validator.methods.rangelength, $.format("This field must contain between {0} and {1} characters"));
$.validator.addClassRules("validate-number", { validateNumber: true });
$.validator.addClassRules("validate-number-min", { validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required-number-min", { validateRequired: true, validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required", { validateRequired: true });
$.validator.addClassRules("validate-rangelengthmax6", { validateRangelength: [0,6] });
}
DefineValidationRules();
You can also add your own custom validation method:
function ValidateInteger(value) {
//do whatever you want to check
}
Having an input in knockout:
<input class="validate-required validate-number" type="text" data-bind="value: examplefield, valueUpdate: 'afterkeydown', attr: { attrname: 'itsvalue'}" />
Checking on submit:
$("#yoursubmitbutton").on("click", function () {
var formtosubmit = $("#idofyourform");
//check for validation errors
if (isValid(formtosubmit)) {
formtosubmit.submit();
//
// code to proceed to next step
}
});
function isValid(el) {
var $thisform = el;
$thisform.validate({
errorElement: "label",
errorPlacement: function (error, element) {
//eventual different error placing
if (element.attr("name") == "fname" || element.attr("name") == "lname") {
element.css("border", "2px solid red");
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
return $thisform.valid();
}

keep the Ids of selected results of Kendo UI Autocomplete in a hidden input

I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK

jQuery dialog for a partial view is not opening modal

I have built a jquery dialog to show a partial view for entering data.
I have built the action link:
#Html.ActionLink("Add New Service Provider", "PartialNewCust", "Customer", null, new { #class = "addServiceProviderLink" })
I have the controller action:
public ActionResult PartialNewCust()
{
return PartialView();
}
And the div / jQuery code:
<div id="AddServiceProvDialog" title="Add Service Provider"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".addServiceProviderLink").button();
$('#AddServiceProvDialog').dialog(
{
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons:
{
"Add": function () {
$("#addProviderForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".addServiceProviderLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#AddServiceProvDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#addProviderForm");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
return false;
});
});
});
The partial view renders fine but opens a new page and does not come up as a modal dialog.
What am I doing wrong.
On a side note: my autocomplete code is also not working by my jQuery datetime picker is...
$(document).ready(function()
{
$(".date").datepicker();
}
);
$(document).ready(function () {
$("#CustByName").autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
}
});
},
minLength: 3
});
});
My guess is that you misplaced the return false statement in the button's click handler, thus the default behavior is not prevented as you expect, and the link is simply followed:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
dialogDiv.html(data);
...
dialogDiv.dialog('open');
// this return statement should be in the "click" handler,
// not in success callback of the .get() method !
return false;
});
});
Your code should then be:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
...
});
// return here to prevent default click behavior
return false;
});

Colorbox resize on form validation (jQuery validate)

Okay so here's the deal :
I call the form in Colorbox through AJAX, and have set up a callback to handle its validation, which works fine. Only problem is, when I try to resize the box when fields are invalid (which generates a label with a class of error), in only works on the second try.
I call the resize method on a click event, and it works only at the second click.
I suspect this is because it tries to resize before the labels are generated...I don't know how to circumvent that issue. Any help would be appreciated.
$(".colorbox").click(function(e) {
e.preventDefault();
var el = $(this),
sdHref = (el.attr("data-sd-href") ? el.attr("data-sd-href") : el.attr("href")),
sdTitle = (el.attr("data-sd-title") ? el.attr("data-sd-title") : el.attr("title")),
sdIframe = (el.attr("data-sd-iframe") ? true : false),
sdWidth = (el.attr("data-sd-width") ? el.attr("data-sd-width") : false),
sdHeight = (el.attr("data-sd-height") ? el.attr("data-sd-height") : false);
$.colorbox({
href: sdHref,
title: sdTitle,
iframe: sdIframe,
width: sdWidth,
height: sdHeight,
scrolling: false,
onComplete: function() { // I validate the form once the content is loaded
$("form").validate({
rules: {
phone: {
minlength: 10,
maxlength:10,
digits: true
}
}
});
}
});
});
$('body').click(function(event) { // Even bubbling works on clicking the button, but only on the second try...
if ($(event.target).is('button[type=submit]')) {
$.colorbox.resize();
}
});
my solution:
$('#form_nuevo_almacen').validate({
rules: {
nombre: {
required: true,
},
clave: {
required: true,
}
},
messages: {
nombre: {
required: "Almacen requerido",
},
clave:{
required:'Clave requerida',
}
},
showErrors: function(errorMap, errorList) {
this.defaultShowErrors();
$.colorbox.resize();
},
submitHandler: function(form){
form.submit();
$.colorbox.close();
}
});
I found the solution :
$(".colorbox").click(function(e) {
e.preventDefault();
var el = $(this),
sdHref = (el.attr("data-sd-href") ? el.attr("data-sd-href") : el.attr("href")),
sdTitle = (el.attr("data-sd-title") ? el.attr("data-sd-title") : el.attr("title")),
sdIframe = (el.attr("data-sd-iframe") ? true : false),
sdWidth = (el.attr("data-sd-width") ? el.attr("data-sd-width") : false),
sdHeight = (el.attr("data-sd-height") ? el.attr("data-sd-height") : false);
$.colorbox({
href: sdHref,
title: sdTitle,
iframe: sdIframe,
width: sdWidth,
height: sdHeight,
scrolling: false,
onComplete: function() { // I validate the form once the content is loaded
$("form").validate({
rules: {
phone: {
minlength: 10,
maxlength:10,
digits: true
}
},
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
window.setTimeout('$.colorbox.resize()',10);
}
}
});
}
});
});

Resources