function OralSaving(e) {
OralValidate(e);
if (e.model.isNew()) {
$('#Oraldosegrid').data('kendoGrid').dataSource.read();
$('#Oraldosegrid').data('kendoGrid').refresh();
}
}
Thursday, October 15, 2015
How to reload Kendo Grid Datasource and reload grid
An example in the Save event of the grid:
Editor Template not binding to model on Grid Popup Save
I had a kendo grid that used popup edit mode. On the popup editor template had a typical Razor @Html.EditorFor(model => model.fk_DrugBrandID)
When editing/adding a record, the editor correctly showed a drop down list of items, but on save, it was not updating the model. Spent hours trying to figure it out, then realized I had encountered this before. It is because the grid does not handle nullable foreign keys! The solution is to use the Save Event of the grid to something like this:
When editing/adding a record, the editor correctly showed a drop down list of items, but on save, it was not updating the model. Spent hours trying to figure it out, then realized I had encountered this before. It is because the grid does not handle nullable foreign keys! The solution is to use the Save Event of the grid to something like this:
//grid doesn't handle nullable foreign keys, this passes the value to the controller
function tvyascoSave(e) {
/*alert('saving: ' + e.model.fk_DrugBrandID);*/
if (!e.model.fk_DrugBrandID) {
//change the model value
e.model.fk_DrugBrandID = 0;
//get the currently selected value from the DDL
var currentlySelectedValue = $(e.container.find('[data-role=dropdownlist]')[0]).data().kendoDropDownList.value();
//set the value to the model
e.model.set('fk_fk_DrugBrandID', currentlySelectedValue);
}
}
Wednesday, June 24, 2015
Grid PopupEdit with file Upload
Using the grid in popup edit mode requires a template for the popup screen, here is that template:
The trick to getting the value is to use the onSuccess event of the upload control to set the hidden field to the value of the uploaded file.
Then in the Grid Save Event, update the "model" to the value of this hidden field.
<div>
<div class="editor-label">
<b>Your Saved Search to Use:</b>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.savedSearchID,"SavedSearchesTemplate")
@Html.ValidationMessageFor(model => model.savedSearchID)
</div>
</div>
@Html.HiddenFor(m => m.ApplicationFile);
<div>
<div class="editor-label">
<b>Project Plan Document:</b>
</div>
<div class="editor-field">
@(Html.Kendo().Upload()
.Name("files")
.Events(events => events.Success("onSuccess"))
.Multiple(false)
.Async(a => a.Save("Save", "Projects").AutoUpload(true)
))
</div>
</div>
The trick to getting the value is to use the onSuccess event of the upload control to set the hidden field to the value of the uploaded file.
function onSuccess(e) {
$("#ApplicationFile").val(getFileInfo(e));
}
Then in the Grid Save Event, update the "model" to the value of this hidden field.
function saving(e) {
var uid = $(".k-edit-form-container").closest("[data-role=window]").data("uid"),
model = $("#myprojectsgv").data("kendoGrid").dataSource.getByUid(uid);
var thefile = $("#ApplicationFile");
model.set("ApplicationFile",thefile.val());
}
Thursday, May 14, 2015
Kendo DropDownList triggering Select Event Programatically
I struggled trying to select an item in a Kendo dropdownlist programmatically and firing the corresponding select event.
Here's the solution. Specifying .trigger("select") would fire the event, but the select function parameter "e" had no values. To reconcile pass in the selected list item, using this syntax:
Here's the solution. Specifying .trigger("select") would fire the event, but the select function parameter "e" had no values. To reconcile pass in the selected list item, using this syntax:
dl.trigger("select", { item: $("li.k-state-selected", $("#dlTableNames-list")) }
@(Html.Kendo().DropDownListFor(model => model)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetTableList", "Lists");
});
})
.DataTextField("DisplayName")
.DataValueField("id")
//.DataValueField("ANAPatternDesc")
//.SelectedIndex(0)
.Name("dlTableNames")
.OptionLabel("- Please select -")
.Events(e => {
e.Select("TableSelected");
// e.Change("TableSelected");
// e.Cascade("TableSelected");
})
.ValuePrimitive(true)
.HtmlAttributes(new { style = "width:400px" })
)
<script>
var dl = $("#dlTableNames").data("kendoDropDownList");
//Select an item by Value:
dl.value(5);
dl.trigger("select", { item: $("li.k-state-selected", $("#dlTableNames-list")) }
function TableSelected(e) {
var item = e.item;
//The display text (not value) of the selected drop down list item:
var text = item.text();
//Reference the kendo dropdownlist:
var dl = $("#dlTableNames").data("kendoDropDownList").dataSource;
var dataItem = this.dataItem(e.item.index());
//The id of the selected drop down list item:
var dataId = this.dataItem(e.item).id;
//Name used for parent div , also used for subdiv (prefixed with "subdiv"xxx):
var divid = text.replace(/\s+/g, '').replace(/\//g, '').replace(/\(/g, '').replace(/\)/g, '') + '_' + dataId;
//Create the parent level div, to which checkboxes will be added to via function => createCheckBox:
createSubElementDiv(divid, text);
//Remove the selected item from the dropdownlist, so the user won't have duplicates:
dl.remove(dl.at(e.item.index()));
//Via ajax, Get sublist of items and render to div as checkboxes:
var link = "@Url.Action("GetSubLists", "Lists", new { id = -1 })";
//Replace -1 with the id of the selected item, input parameter of the controller action method:
link = link.replace("-1", dataId);
$.ajax({
cache: false,
type: "GET",
dataType: "json",
contentType: "application/json; carset=utf-8",
url: link,
data: { "id": text },
success: function (data) {
name = data;
// For each line in json object, create a checkbox:
$.each(data, function (key, value) {
createCheckBox('subdiv' + divid, value.id, value.Text);
});
},
error: function (xhr, ajaxOptions, thrownError) {
customMsg('An error occurred loading data. The Administrator has been notified.' + thrownError);
}
});
//Collapse the drop down list:
$("#dlTableNames").data("kendoDropDownList").close();
return false;
}
</script>
Tuesday, May 12, 2015
Using a Kendo Window like a javascript prompt to get input
Create the following div:
<div id="inputWindow">
<label for="userinput">Save Search as Name:</label>
<input type="text" name="userinput" id="userinput" title="Search Name" />
</div>
Call showSaveAsDialog()
If the user does not enter a value in the textbox, the function exits. If they do and close the popup window, the function continues, writing data to the controller via ajax:
var saveName = '';
var handleUserInput = function () {
var userinput = ($("#userinput").val());
if (userinput.length == 0) {
alert('A name for the saved filter is required.');
return;
}
else {
saveName = userinput;
//
var list = [];//The final output list
$('.formFieldWrapper').each(function () {
//get the id of the parent DIV containter:
var parentid = this.id;
var index = parentid.lastIndexOf("_");
//Get the ID for the parent as stored in db table TableList
var FilterTableID = parentid.substr(index + 1);
//Foreach checkbox checked in this parent:
$('#' + parentid + ' input:checked').each(function () {
//Populate Object Literal with the uid of the selected table ( into FilterTableID),
list.push({ id: this.id.replace('ck', ''), FilterTableID: FilterTableID });
});
});
var userid = "@User.Identity.GetUserId()";
var url = "@Url.Action("SaveFilter", "SaveFilter", new { id = -1 , SavedName = -2, jsonData = -3 })";
//Replace -1 with the id of the selected item, input parameter of the controller action method:
url = url.replace("-1", userid);
url = url.replace("-2", saveName);
url = url.replace("-3", $.toJSON(list));
$.ajax({
cache: false,
type: "POST",
dataType: "html",
contentType: "application/json; carset=utf-8",
url: url,
success: function (data) {
alert('saved');
},
error: function (xhr, ajaxOptions, thrownError) {
customMsg(' Save Search', 'Oh Oh, An error occurred while attempting to save your search. The Administrator has been notified.' + thrownError);
}
});
}
}
function showSaveAsDialog() {
var win = $("#inputWindow")
.kendoWindow({
actions: ["Maximize", "Close"],
animation: {
open: {
effects: "slideIn:down fadeIn",
duration: 500
},
close: {
effects: "slide:up fadeOut",
duration: 500
}
},
minWidth: 300,
modal: true,
resizable: true,
title: "Name to save the Filter As",
visible: false,
close: handleUserInput
})
.data("kendoWindow")
.center();
var wrapper = win.wrapper;
wrapper.css({ top: 25 });
win.open();
}
Friday, May 8, 2015
Kendoh Dropdownlist value undefined!
I tried for hours to get the value from a kendo dropdownlist, to no avail. It was driving me nuts.
It has a method calld .value() - that didn't work, dataItem.value did not work either.
Finaaly out of desperation, I realized that I had the data item, and thought, perhaps it contains the field names, just like the json delivered to it. The solution was simply to specify dataItem.xxx where xxx is the name of the field I wanted to the value from. Here's the code example:
JavaScript to get the value:
Note the commented line, this feature is cool, if the drop downlist is not data bound it will return an empty array, otherwise it will return an array of itesm
It has a method calld .value() - that didn't work, dataItem.value did not work either.
Finaaly out of desperation, I realized that I had the data item, and thought, perhaps it contains the field names, just like the json delivered to it. The solution was simply to specify dataItem.xxx where xxx is the name of the field I wanted to the value from. Here's the code example:
@(Html.Kendo().DropDownListFor(model => model)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetTableList", "Lists");
});
})
.DataTextField("DisplayName")
.DataValueField("id")
//.DataValueField("ANAPatternDesc")
//.SelectedIndex(0)
.Name("dlTableNames")
.OptionLabel("- Please select -")
.Events(e => e.Select("TableSelected"))
.ValuePrimitive(true)
.HtmlAttributes(new { style="width:400px" })
)
JavaScript to get the value:
function TableSelected(e) {
var item = e.item;
var text = item.text();
var dl = $("#dlTableNames").data("kendoDropDownList").dataSource;
var dataItem = this.dataItem(e.item);
//alert($("#dlTableNames").getKendoDropDownList().dataSource.data().length);
alert(dataItem.id);
Note the commented line, this feature is cool, if the drop downlist is not data bound it will return an empty array, otherwise it will return an array of itesm
Tuesday, March 31, 2015
Cool Stuff, Editable Grid with Automatic Changes saved
This is ideal for checkboxes. Placing a grid in .Batch(true) and .ServerOperation(false) allows the user to click on a cell to edit it's value. Usually there is a "Save Changes" button they have to click to save all their changes.
In this solution we allow users to check or uncheck checkboxes - when they change the state of a checkbox, it updates the database automatically - no need to have the user click the save changes button.
Create a template column:
Add a change event to the grid's datasource:
Add the JavaScript event and code for the template checkbox:
The checkbox javascript code updates the in memory model with the new value of the control, the dataChange function saves the changes to the database (calls the grid's Update method).
BTW, the code formatting for this blog post was done using this handy tool:
http://codeformatter.blogspot.com/
In this solution we allow users to check or uncheck checkboxes - when they change the state of a checkbox, it updates the database automatically - no need to have the user click the save changes button.
Create a template column:
c.Bound("ArticleIsMine").ClientTemplate("<input type='checkbox' #= ArticleIsMine? checked='checked': checked='' # class='chkbx' />");
Add a change event to the grid's datasource:
.DataSource(data => data.Ajax()
.Model( m =>
{
m.Id("Id");
m.Field(f => f.PubDate).Editable(false);
m.Field(f => f.Title).Editable(false);
})
.Events(e => e.Change("dataChange"))
Add the JavaScript event and code for the template checkbox:
$(document).ready(function () {
kendo.data.DataSource.prototype.options.autoSync = true;
$('#gvPubs').on('click', '.chkbx', function () {
var checked = $(this).is(':checked');
var g = $('#gvPubs').data().kendoGrid;
g.closeCell();
var dataItem = g.dataItem($(this).closest('tr'));
var col = $(this).closest('td');
g.editCell(col);
dataItem.set(g.columns[col.index()].field, checked);
g.closeCell(col);
});
the sync call does the actual save: function dataChange(e) {
if (e.action == "itemchange") {
this.sync();
}
}
The checkbox javascript code updates the in memory model with the new value of the control, the dataChange function saves the changes to the database (calls the grid's Update method).
BTW, the code formatting for this blog post was done using this handy tool:
http://codeformatter.blogspot.com/
Subscribe to:
Posts (Atom)