I was returning Json(list) from the controller causing this issue, it was resolved by returning View(list) instead, full code for functional system follows:
CSHTML:
@using Kendo.Mvc.UI
@model IEnumerable<DynaResearchPortal.Models.ImportDTO>
@{
ViewBag.Title = "PreviewData";
Layout = "~/Views/Shared/_LayoutPage.cshtml";
}
<h2>Preview Data</h2>
@(Html.Kendo().Grid(Model)
.Name("PreviewGrid")
.Columns(c =>
{
c.Bound(t => t.ColumnName);
c.Bound(t => t.Ordinate);
}
)
)CONTROLLER:
public ActionResult PreviewData(string filename)
{
List<ImportDTO> list = new List<ImportDTO>();
ISheet sheet;
using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook wb = new HSSFWorkbook(file);
sheet = wb.GetSheetAt(0);
//Get the Title row:
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
ImportDTO dto = new ImportDTO();
dto.ColumnName = headerRow.GetCell(i).StringCellValue.Trim();
dto.Ordinate = i;
list.Add(dto);
}
}
return View(list);
}
Thursday, July 28, 2016
Tuesday, May 17, 2016
Disable update button on grid popup
If your grid is in popup edit mode and you want to disable the Update button, use this js:
$('.k-grid-update').css('display', 'none');
$('.k-grid-update').css('display', 'none');
Monday, May 9, 2016
Kendo Dropdownlist change function syntax
This delayed my coding progress for quite sometime, I was trying to bind a js function to the change event of a drop down list, the syntax I was using was like:
$("#srch" + i).kendoDropDownList({
optionLabel: "- Please select -",
dataTextField: "DisplayName",
dataValueField: "savedSearchID",
change: "searchOnChange",
dataSource: json
});
I couldn't figure out why it was blowing up. Quite simple fix, remove the quotes around the function name, so this worked (note quotes removed from searchOnChange):
$("#srch" + i).kendoDropDownList({
optionLabel: "- Please select -",
dataTextField: "DisplayName",
dataValueField: "savedSearchID",
change: searchOnChange,
dataSource: json
});
$("#srch" + i).kendoDropDownList({
optionLabel: "- Please select -",
dataTextField: "DisplayName",
dataValueField: "savedSearchID",
change: "searchOnChange",
dataSource: json
});
I couldn't figure out why it was blowing up. Quite simple fix, remove the quotes around the function name, so this worked (note quotes removed from searchOnChange):
$("#srch" + i).kendoDropDownList({
optionLabel: "- Please select -",
dataTextField: "DisplayName",
dataValueField: "savedSearchID",
change: searchOnChange,
dataSource: json
});
Thursday, April 28, 2016
How to fix grid from not refreshing after create or update (add/edit record)
Solution is to refresh the grid using javascript on the data source requestend event.
Here's how:
Add this Javascript:
Then in the razor code for the grid:
Here's how:
Add this Javascript:
function OnRequestEnd(e) {
if (e.type === "update" || e.type === "create") {
var grid = $('#myprojectsgv').data('kendoGrid');
grid.dataSource.read();
}
}
Then in the razor code for the grid:
.DataSource(data => data.Ajax()
.Model(model =>
{
model.Id(record => record.projectID);
})
.Sort(m => m.Add("projectID").Descending())
//.ServerOperation(false)
.Read(read => read.Action("GetMyProjects", "Projects").Data("getUserID"))
.Create(create => create.Action("CreateProject", "Projects"))
.Update(update => update.Action("UpdateProject", "Projects"))
.Destroy(delete => delete.Action("DeleteProject", "Projects"))
.PageSize(10)
.Batch(false)
.Events(e =>
{
e.Error(@<text>
function(e) {
griderror(e,"myprojectsgv", "My Projects");
}
</text>);
e.RequestEnd("OnRequestEnd");
})
)
Wednesday, November 25, 2015
Violation of Foreign Key
When using the grid in editmode popu with a editor template, was getting a Violation of a Foreign Key, debugging, I could see the fk value was being set, but it was blowing up in the DbSet.Add function. Thought it was the editor template configuration, but it wasn't. The table loaded in the drop downlist editor template was using a class called "InsurancePlan" - used to set the fk value - the grid was saving an "Insurance" object. The problem turns out because the InsurancePlan class included a virtual ICollection<Insurance>, but I had commented out the contructor, uncommenting the contructor resolved:
public InsurancePlan()
{
this.Insurances = new List<Insurance>();
}
public InsurancePlan()
{
this.Insurances = new List<Insurance>();
}
Friday, October 23, 2015
Close all kendo windows
$(".k-window-content").each(function(){ $(this).data("kendoWindow").close();});Thursday, October 15, 2015
Sort a kendo grid from razor configuration
Simple, add sort instructions to the data source:
.DataSource(data => data.Ajax()
.Model(model =>
{
model.Id(record => record.doseID);
model.Field(m => m.drugID).DefaultValue(23);
})
.Read(read => read.Action("GetPatientDoses", "PHMedications", new { id = @queryValue, drug = 23, isIV = false, isSQ = false }))
.Create(create => create.Action("DoseCreate", "PHMedications").Data("GetqueryValue"))
.Update(update => update.Action("DoseUpdate", "PHMedications"))
.Destroy(delete => delete.Action("DoseDelete", "PHMedications"))
.Sort(m =>
{
m.Add("doseEndDate").Ascending();
m.Add("doseStartDate").Descending();
})
.PageSize(2)
How to reload Kendo Grid Datasource and reload grid
An example in the Save event of the grid:
function OralSaving(e) {
OralValidate(e);
if (e.model.isNew()) {
$('#Oraldosegrid').data('kendoGrid').dataSource.read();
$('#Oraldosegrid').data('kendoGrid').refresh();
}
}
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/
Monday, March 30, 2015
How to make a Kendo UI Grid cell non-editable:
How to make a Kendo UI Grid cell non-editable:
In the data source, make the field editable(false):
In the data source, make the field editable(false):
.DataSource(data => data.Ajax()
.Model( m =>
{
m.Id("Id");
m.Field(f => f.PubDate).Editable(false);
m.Field(f => f.Title).Editable(false);
})
Wednesday, March 4, 2015
Cancel/Close the Grid Popup Editor Window
I had a requirement that if a condition was met, when a user clicked Add New Record, it would close the popup window, and display a message instead, accomplished with js like this:
function editmode(e) {
if (e.model.isNew()) {
var target = $("#cathTestDate").data("kendoDropDownList");
var len = target.dataSource.data().length;
e.preventDefault();
this.editRow($(e.currentTarget).closest("tr"));
alert(len);
}
}
Declare in the grid:
@(Html.Kendo().Grid<Model.Models.CathReport>()
.Name("cathreportgrid")
.Events(e => {
e.Edit("editmode");
})
function editmode(e) {
if (e.model.isNew()) {
var target = $("#cathTestDate").data("kendoDropDownList");
var len = target.dataSource.data().length;
e.preventDefault();
this.editRow($(e.currentTarget).closest("tr"));
alert(len);
}
}
Declare in the grid:
@(Html.Kendo().Grid<Model.Models.CathReport>()
.Name("cathreportgrid")
.Events(e => {
e.Edit("editmode");
})
Wednesday, February 25, 2015
Grid Popup Editing Template, show/hide field based on another bit field.
We have a grid that used a template editor for poup editing.
We have a bool field that if clicked, we want to show the corresponding value field, otherwise, hide it.
I gave the div that I want to hide/show an ID and set it's visibility to hidden (the first editor is the bool field):
<div>
<div class="editor-label">
<b>Right Ventricular Hypertrophy?</b>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IsRightVentHypertrophy)
@Html.ValidationMessageFor(model => model.IsRightVentHypertrophy)
</div>
</div>
<div id="RVentFuncDiv" style="visibility: hidden; z-index: 9999;">
<div class="editor-label">
<b>Right Ventricular Function:</b>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.fk_RightVentricularFunctionID, "RVFunction")
@Html.ValidationMessageFor(model => model.fk_RightVentricularFunctionID)
</div>
</div>
I created the following js function on the editor template:
function checkit(parent, child) {
if ($("#" + parent).is(':checked'))
$("#" + child).css("visibility", "visible");
else
$("#" + child).css("visibility", "hidden");
}
and called it on it's document.ready:
$(document).ready(function () {
$("#IsRightVentHypertrophy").change(function () {
checkit("IsRightVentHypertrophy", "RVentFuncDiv");
});
});
Back on the main page the grid was assigned an event for edit:
.Name("echogrid")
.Events(e =>
{
e.Edit("editmode");
})
An here is the js function for that event:
function editmode(e) {
checkit("IsRightVentHypertrophy", "RVentFuncDiv");
}
We have a bool field that if clicked, we want to show the corresponding value field, otherwise, hide it.
I gave the div that I want to hide/show an ID and set it's visibility to hidden (the first editor is the bool field):
<div>
<div class="editor-label">
<b>Right Ventricular Hypertrophy?</b>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IsRightVentHypertrophy)
@Html.ValidationMessageFor(model => model.IsRightVentHypertrophy)
</div>
</div>
<div id="RVentFuncDiv" style="visibility: hidden; z-index: 9999;">
<div class="editor-label">
<b>Right Ventricular Function:</b>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.fk_RightVentricularFunctionID, "RVFunction")
@Html.ValidationMessageFor(model => model.fk_RightVentricularFunctionID)
</div>
</div>
I created the following js function on the editor template:
function checkit(parent, child) {
if ($("#" + parent).is(':checked'))
$("#" + child).css("visibility", "visible");
else
$("#" + child).css("visibility", "hidden");
}
and called it on it's document.ready:
$(document).ready(function () {
$("#IsRightVentHypertrophy").change(function () {
checkit("IsRightVentHypertrophy", "RVentFuncDiv");
});
});
Back on the main page the grid was assigned an event for edit:
.Name("echogrid")
.Events(e =>
{
e.Edit("editmode");
})
An here is the js function for that event:
function editmode(e) {
checkit("IsRightVentHypertrophy", "RVentFuncDiv");
}
Monday, February 16, 2015
Lousy built in Exporting
the 2014 3rd quarter release of Kendo grid has export capability via commands, it sucks.
Because, instead of exporting the data as displayed in the grid, it will export the underlying values instead. If you use templates that is:
"Yes, by design the data from the data source is exported. If a grid column has its template set it will be ignored. Templates can be arbitrary HTML which doesn't translate to Excel. If the template isn't HTML you can manually use it as shown in this help article: http://docs.telerik.com/kendo-ui/web/grid/how-to/excel/column-template-export
"
If you are not using templates then you might find this article useful:
http://developer.telerik.com/featured/exporting-data-ease-using-kendo-ui-grid/
Because, instead of exporting the data as displayed in the grid, it will export the underlying values instead. If you use templates that is:
"Yes, by design the data from the data source is exported. If a grid column has its template set it will be ignored. Templates can be arbitrary HTML which doesn't translate to Excel. If the template isn't HTML you can manually use it as shown in this help article: http://docs.telerik.com/kendo-ui/web/grid/how-to/excel/column-template-export
"
If you are not using templates then you might find this article useful:
http://developer.telerik.com/featured/exporting-data-ease-using-kendo-ui-grid/
Friday, December 26, 2014
DropDown Displaying Json Date in DataTextField
I had a foreign key kendo drop down list editor template, and the DataTextField was pointed to a DateTime field, it was displaying items in the dropdown in the following json format:
/Date(1124859600000)/
The solution to display it as a simple date was to utilize templates using Kendo Format:
@using Kendo.Mvc.UI
@model IQueryable<Model.Models.OfficeVisit>
@{var val = string.Empty;
if (Request.QueryString["id"] != null)
{
val = Request.QueryString["id"];
}
else
{
//No Querystring, so use the id from action call:
val = Url.RequestContext.RouteData.Values["id"].ToString();
}
}
@{
Layout = null;
}
<script>
function GetValue() {
return {
Id: "@val"
};
}
</script>
@(Html.Kendo().DropDownList()
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetPatientOfficeVisits", "OfficeVisits").Data("GetValue()");
});
})
.DataTextField("VisitDate")
.TemplateId("dltemplate")
.ValueTemplateId("dltemplate")
.DataValueField("pk_OfficeVisitID")
//.DataValueField("ANAPatternDesc")
//.SelectedIndex(0)
.Name("fk_OfficeVisitID")
.OptionLabel("- Please select -")
.HtmlAttributes(new { data_value_primitive = true })
)
<script type="text/x-kendo-template" id="dltemplate">
#:kendo.toString(kendo.parseDate(data.VisitDate), 'MM/dd/yyyy') #
</script>
/Date(1124859600000)/
The solution to display it as a simple date was to utilize templates using Kendo Format:
@using Kendo.Mvc.UI
@model IQueryable<Model.Models.OfficeVisit>
@{var val = string.Empty;
if (Request.QueryString["id"] != null)
{
val = Request.QueryString["id"];
}
else
{
//No Querystring, so use the id from action call:
val = Url.RequestContext.RouteData.Values["id"].ToString();
}
}
@{
Layout = null;
}
<script>
function GetValue() {
return {
Id: "@val"
};
}
</script>
@(Html.Kendo().DropDownList()
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetPatientOfficeVisits", "OfficeVisits").Data("GetValue()");
});
})
.DataTextField("VisitDate")
.TemplateId("dltemplate")
.ValueTemplateId("dltemplate")
.DataValueField("pk_OfficeVisitID")
//.DataValueField("ANAPatternDesc")
//.SelectedIndex(0)
.Name("fk_OfficeVisitID")
.OptionLabel("- Please select -")
.HtmlAttributes(new { data_value_primitive = true })
)
<script type="text/x-kendo-template" id="dltemplate">
#:kendo.toString(kendo.parseDate(data.VisitDate), 'MM/dd/yyyy') #
</script>
Monday, December 15, 2014
How to update an EditorFor that uses a kendo NumericTextBoxFor control.
Easy to get a value using .val(), but to set the value you have to call the change event of the control and navigate away from it in order to save the changes to the model!
@Html.EditorFor(model => model.PVR, "Number")
Here's the editorTemplate named "Number":
@model double?
@using Kendo.Mvc.UI
@(Html.Kendo().NumericTextBoxFor(m => m)
.Decimals(3)
.Format("0.000")
.HtmlAttributes(new { style = "width:100%" })
)
here's the jscript code to update the value:
var kendo = $("#PVR").data("kendoNumericTextBox");
kendo.value(output);
kendo.trigger("change");
var target = $("#Wedge").data("kendoNumericTextBox");
target.siblings("input:visible").focus();
@Html.EditorFor(model => model.PVR, "Number")
Here's the editorTemplate named "Number":
@model double?
@using Kendo.Mvc.UI
@(Html.Kendo().NumericTextBoxFor(m => m)
.Decimals(3)
.Format("0.000")
.HtmlAttributes(new { style = "width:100%" })
)
here's the jscript code to update the value:
var kendo = $("#PVR").data("kendoNumericTextBox");
kendo.value(output);
kendo.trigger("change");
var target = $("#Wedge").data("kendoNumericTextBox");
target.siblings("input:visible").focus();
Subscribe to:
Posts (Atom)