Hi Team,
We are using Kendo ListBox in our application. This can have, say a list of countries. Once user types a letter, the first record with that letter should be selected (similar behaviour like in dropdowns). Please advise how this can be achieved.
Thanks,
Faraaz
I am using a KendoUI treeview. The treeview contain 13 anchor tags . This anchor tags are basically questions. On clicking each Anchor tag, I am making a Ajax call and on Ajax success , I am returning a Partial View as html in the div tag. The Partial view contains textarea and KendoUI grid.
The html is loaded correctly in the div tag with text area and grid .However the console is showing error "Uncaught ReferenceError: onDataBound is not defined"
How do I fix the error ? Should I use Deferred Initialization ?
https://docs.telerik.com/aspnet-mvc/getting-started/helper-basics/fundamentals?&_ga=2.185465772.48909972.1612825511-1665294203.1606507004#deferring-initialization
Also, when I try to test .Read,.Create,.Destroy, .Update, the code does not hit the controller.
Should I move the javascript code for the KendoUI grid in the PartialView to the global javascript file ?How do I make the Kendo UI grid work in Partial View after Ajax success ? A project with example will be helpful?
Index.cshtml : (Displaying html)
<div id="divQuestions">
</div>
Ajax Call:
if (id != null) {
$.ajax({
type: "POST",
url: Globals.BaseUrl + "Questions/SaveTocAndShowQuestions/?questionNo=" + tocquestionNo + "&displayNumber=" + tocdisplayNo + "§ionId=" + SectionId + "&subSectionId=" + SubSectionId,
dataType: "html",
async: true,
cache: false,
data: serializedForm,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result, textStatus, jqXHR) {
// window.location.href = result;
// console.log(result);
if ($("#divQuestions").length) {
$('#divQuestions').html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + ajaxOptions + "," + thrownError + "," + xhr.responseText);
}
});
Partial View Containing KendoUI Grid
<div id="pnReporterCommentsGrid">
@(Html.Kendo().Grid<FYQuestionCommentsInfo>()
.Name("ReporterCommentGrid")
.Columns(columns =>
{
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
columns.Bound(m => m.RECORD_TYPE)
.Title("Record Type");
columns.Bound(m => m.RECORDED_DATE).Format("{0:G}")
.Title("Returned Date");
columns.Bound(m => m.USERID)
.Title("Returned By");
columns.Bound(m => m.COMMENTS)
.Title("Comments");
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Item"))
.Resizable(resize => resize.Columns(true))
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("FYQuestionsCommentsInfo").Window(w => w.Title("Edit").Name("customedit").Width(1000)))
// .Events(e => e.Edit("HideGridFields"))
.Events(e => e.DataBound("onDataBound"))
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
// .ServerOperation(false)
.Events(events => events
.Sync("RefreshReporterCommentGrid"))
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(m => m.QuestionCommentsInfoId);
model.Field(m => m.QuestionCommentsInfoId).Editable(false);
model.Field(m => m.USERID).DefaultValue(Model.upacsUserViewModel.Username);
model.Field(m => m.RECORDED_DATE).Editable(false);
})
.Read(read => read.Action("Bind_Reporter", "Questions").Data("sendAntiForgery"))
.Create(update => update.Action("CreateReporterComments", "Questions").Data("sendAntiForgery"))
.Destroy(d => d.Action("DestroyReporterComments", "Questions").Data("sendAntiForgery"))
.Update(update => update.Action("UpdateReporterComments", "Questions").Data("sendAntiForgery"))
)
)
</div>
<script type="text/javascript">
function HideGridFields(e) {
HideControl("QuestionCommentsInfoId", e);
HideControl("REGION", e);
HideControl("STATE_CODE", e);
HideControl("FiscalYear", e);
HideControl("REPORT_ID", e);
HideControl("SECTION_ID", e);
HideControl("SUBSECTION_ID", e);
HideControl("QUESTION_NUMBER", e);
HideControl("QUESTION_PART_NUMBER", e);
HideControl("DISPLAY_NUMBER", e);
HideControl("RECORD_TYPE", e);
HideControl("RECORDED_DATE", e);
HideControl("QuestionDetailId", e);
}
function HideControl(fieldName, e) {
var cont = $(e.container);
HideFieldLabel(cont.find("label[for='" + fieldName + "']"));
HideFieldField(cont.find("#" + fieldName));
}
function HideFieldLabel(control) {
control.parent(".editor-label").hide();
}
function HideFieldField(control) {
control.parent(".editor-field").hide();
}
function RefreshReporterCommentGrid() {
var grid = $('#ReporterCommentGrid').data('kendoGrid');
grid.dataSource.read();
}
function onDataBound(e) {
var grid = $('#ReporterCommentGrid').data('kendoGrid');
var gridData = grid.dataSource.view();
for (var i = 0; i < gridData.length; i++) {
var currentUid = gridData[i].uid;
if (gridData[i].RECORDED_DATE != null) {
var currenRow = grid.table.find("tr[data-uid='" + currentUid + "']");
var editButton = $(currenRow).find(".k-grid-edit");
var deleteButton = $(currenRow).find(".k-grid-delete");
if (('@Model.upacsUserViewModel.HSIPUserType' == 'SuperReporter') || ('@Model.upacsUserViewModel.HSIPUserType' == 'Reporter'))
{
if ('@Model.FiscalYear' == '@Constants.Year')
{
if (gridData[i].RECORD_TYPE == 'Reporter Comments')
{
editButton.show();
deleteButton.show();
}
else if ((gridData[i].RECORD_TYPE == 'Reviewer Approve Comments') || (gridData[i].RECORD_TYPE == 'Reviewer Return Comments'))
{
editButton.hide();
deleteButton.hide();
}
}
else
{
editButton.hide();
deleteButton.hide();
}
}
else
{
editButton.hide();
deleteButton.hide();
}
}
}
}
function sendAntiForgery() {
return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }
}
function error_handler(e, status) {
$('#ReporterCommentGrid').data('kendoGrid').cancelChanges();
if (e.errors) {
var message = "\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
I am using a KendoUI treeview. The treeview contain 13 anchor tags . This anchor tags are basically questions. On clicking each Anchor tag, I am making a Ajax call and on Ajax success , I am returning a Partial View as html in the div tag. The Partial view contains KendoUI grid.
When the partial view is rendered, it only displays an empty grid without data in it.
How do I get it to work in Partial View
However the console is showing error "Uncaught ReferenceError: onDataEdit is not defined"
Index.cshtml : (Displaying html)
<div id="divQuestions">
</div>
Ajax Call:
if (id != null) {
$.ajax({
type: "POST",
url: Globals.BaseUrl + "Questions/SaveTocAndShowQuestions/?questionNo=" + tocquestionNo + "&displayNumber=" + tocdisplayNo + "§ionId=" + SectionId + "&subSectionId=" + SubSectionId,
dataType: "html",
async: true,
cache: false,
data: serializedForm,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result, textStatus, jqXHR) {
// window.location.href = result;
// console.log(result);
if ($("#divQuestions").length) {
$('#divQuestions').html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + ajaxOptions + "," + thrownError + "," + xhr.responseText);
}
});
Partial View
<div id="pvRHCPGridQuestion7">
<p><b>Input the number of crossings and program emphasis areas by crossing type.</b></p>
@Html.AntiForgeryToken()
@(Html.Kendo().Grid<HSIP.Domain.Grid7DomainModel>()
.Name("PerformanceGrid")
.Columns(columns =>
{
columns.Bound(m => m.display_num).Hidden();
columns.Bound(m => m.FIXED_ROWS).Hidden();
columns.Bound(m => m.MAX_ROW_NUM).Hidden();
columns.Command(command => { command.Destroy(); }).Width("20%");
//columns.Command(command =>
//{
// command.Custom("Delete").Click("onDataRemove").SendDataKeys(true);
//}).Width("20%");
columns.Bound(m => m.val_description).Title("Crossing Type").HtmlAttributes(new { style = "text-align: left;" }).HeaderHtmlAttributes(new { style = "text-align: center;" });
columns.Bound(m => m.col1).EditorTemplateName("IntegerBox").HtmlAttributes(new { style = "text-align: right;" })
.Title("Number of Crossings").HeaderHtmlAttributes(new { style = "text-align: center;" });
})
.ToolBar(toolbar => {
toolbar.Create().Text("Add New Item");
toolbar.Save().CancelText("Undo");
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Resizable(resize => resize.Columns(true))
.Events(events => events.Edit("onDataEdit").Save("onDataSave").SaveChanges("onSaveChanges"))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Events(events => events.Sync("RefreshGrid"))
.Model(model =>
{
model.Id(m => m.display_num);
model.Field(m => m.display_num).Editable(false);
model.Field(m => m.val_description).Editable(true);
model.Field(m => m.col1).Editable(true);
model.Field(m => m.FIXED_ROWS).Editable(false);
model.Field(m => m.MAX_ROW_NUM).Editable(false);
})
.Sort(sort => sort.Add("display_num").Ascending())
.Create(update => update.Action("Create_Q7_Batch", "Questions").Data("sendAntiForgery"))
.Read(read => read.Action("Bind_Q7", "Questions").Data("sendAntiForgery"))
.Update(update => update.Action("Update_Q7_Batch", "Questions").Data("sendAntiForgery"))
.Destroy(d => d.Action("Destroy_Q7_Batch", "Questions").Data("sendAntiForgery"))
)
)
</div>
<script type="text/javascript">
function sendAntiForgery() {
return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }
}
function onDataRemove(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
if (confirm('Are you sure you want to clear the values?')) {
$.ajax({
type: 'POST',
url: '@Url.Action("CustomDelete_Q7", "Questions")',
data: { display_num: dataItem.display_num },
dataType: "text",
traditional: true,
async: false,
success: function (s) {
if (s.ErrorDetails) {
alert(s.ErrorDetails);
} else {
$('#PerformanceGrid').data("kendoGrid").dataSource.read();
}
},
error: function (s) {
if (s.ErrorDetails) {
alert(s.ErrorDetails);
}
}
});
}
};
function onSaveChanges(e) {
var errors = [];
var dataSource = $('#PerformanceGrid').data("kendoGrid").dataSource;
var rows = dataSource.data();
for (var i = 0; i < rows.length; i++) {
if (rows[i].dirty) {
if ((rows[i].FIXED_ROWS == null || (rows[i].id != null && rows[i].id > rows[i].FIXED_ROWS)) && rows[i].val_description != null && rows[i].val_description.length > 100) {
alert("Maximum length for Performance Measure is 100!");
e.preventDefault();
return;
}
}
}
var validRows = 0;
for (var i = 0; i < dataSource.data().length; i++) {
if (rows[i].dirty) {
if (isNaN(parseInt(rows[i].col1)) == false) {
validRows++;
}
}
else {
validRows++;
}
}
if (validRows < dataSource.data().length) {
e.preventDefault();
alert('Please complete "NUMBER OF CROSSING" for all rows.');
}
}
function onDataSave(e) {
if (e.values.val_description) {
if ((e.model.isNew() || e.model.id > e.model.FIXED_ROWS) && e.values.val_description.length > 100) {
alert("Maximum length for Performance Measure is 100!");
}
}
}
function onDataEdit(e) {
$(".field-validation-valid").empty();
if (e.model.isNew()) {
}
else {
if (e.model.id <= e.model.FIXED_ROWS) {
e.container.find("input[name='val_description']").each(function () { $(this).attr("disabled", "disabled") });
}
}
//$('#col1').kendoNumericTextBox({decimals:0, format: '#', min:0});
}
function RefreshGrid() {
var grid = $('#PerformanceGrid').data('kendoGrid');
grid.dataSource.read();
}
function error_handler(e, status) {
$('#PerformanceGrid').data('kendoGrid').cancelChanges();
if (e.errors) {
var message = "\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
public
static
IQueryable<DetailedTicketModel> GetDetailedTicketModels(IQueryable<TICKET> tickets)
{
using
(var ctx =
new
GuardianContext())
{
var detailedTickets = tickets.Select(v =>
new
DetailedTicketModel()
{
Id = v.ID,
RequesterId = v.REQUESTER_ID,
RequesterName = v.REQUESTER_NAME,
Phone = v.PHONE,
Location = v.LOCATION,
Source = v.SOURCE,
PersonAssigned = v.PERSON_ASSIGNED,
Created = v.CREATED,
Updated = v.UPDATED,
DeptId = v.DEPT_ID,
DeptName = ctx.DEPARTMENTS.FirstOrDefault(t => t.ID == v.DEPT_ID).NAME,
TopicId = v.TOPIC_ID,
TopicName = ctx.TICKET_TOPICS.FirstOrDefault(t => t.ID == v.TOPIC_ID).NAME,
StatusId = v.STATUS_ID,
StatusName = ctx.TICKET_STATUSES.FirstOrDefault(t => t.ID == v.STATUS_ID).NAME,
PriorityId = v.PRIORITY_ID,
PriorityName = ctx.TICKET_PRIORITIES.FirstOrDefault(t => t.ID == v.PRIORITY_ID).NAME,
PriorityHexColor = ctx.TICKET_PRIORITIES.FirstOrDefault(t => t.ID == v.PRIORITY_ID).HEX_COLOR,
TicketEvents = ctx.TICKET_EVENTS.Where(t => t.TICKET_ID == v.ID).OrderBy(t => t.CREATED),
RequestBody =
ctx.TICKET_EVENTS.OrderBy(t => t.CREATED).FirstOrDefault(t => t.TICKET_ID == v.ID).BODY,
RequestFormat =
ctx.TICKET_EVENTS.OrderBy(t => t.CREATED).FirstOrDefault(t => t.TICKET_ID == v.ID).FORMAT,
});
return
detailedTickets;
}
}
public
ActionResult UnassignedTickets_Read([DataSourceRequest]DataSourceRequest request)
{
Debug.WriteLine(
"UnassignedTickets_Read"
);
using
(var ctx =
new
GuardianContext())
{
var detailedTickets =
TicketHelper.GetDetailedTicketModels(ctx.TICKETS.Where(v => v.PERSON_ASSIGNED ==
null
));
//PROBLEM HAPPENS AT THE NEXT STATEMENT
var result = detailedTickets.ToDataSourceResult(request, ticket =>
new
{
ticket.Id,
ticket.RequesterId,
ticket.RequesterName,
ticket.Created,
ticket.RequestBody,
ticket.RequestFormat
});
return
Json(result);
}
}
A first chance exception of type
'System.NotSupportedException'
occurred
in
EntityFramework.dll
A first chance exception of type
'System.NotSupportedException'
occurred
in
EntityFramework.dll
A first chance exception of type
'System.NotSupportedException'
occurred
in
EntityFramework.SqlServer.dll
A first chance exception of type
'System.NotSupportedException'
occurred
in
System.Web.Mvc.dll
A first chance exception of type
'System.NotSupportedException'
occurred
in
System.Web.Mvc.dll
@if (ViewBag.UnassignedTicketsAvailable)
{
<
h3
class
=
"page-header"
>Unassigned Tickets</
h3
>
@(Html.Kendo().Grid<
Guardian.ViewModels.DetailedTicketModel
>()
.Name("unassigned_grid")
.Columns(columns =>
{
columns.Bound(ticket => ticket.Id).Visible(false);
columns.Bound(ticket => ticket.RequesterId);
columns.Bound(ticket => ticket.RequesterName);
columns.Bound(ticket => ticket.Created);
})
.DataSource(dataSource => dataSource.Ajax().Read(read => read.Action("UnassignedTickets_Read", "Ticket"))
)
.ClientDetailTemplateId("client-template")
.Sortable()
.Pageable()
.Filterable()
)
}
<
script
id
=
"client-template"
type
=
"text/kendo-tmpl"
>
@(Html.Raw("<
div
style\"padding: 0.4em;\">#=RequestBody#</
div
>"))
</
script
>
<
script
>
function dataBound() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
</
script
>
My model like this
public
class
MyViewModel
{
public
int
Id {
get
;
set
; }
[DataType(DataType.Date)]
public
DateTime ApplicationDate {
get
;
set
; }
}
My View like this
.DataSource(d => d
.Custom()
.Type(
"aspnetmvc-ajax"
)
.Batch(
true
)
.Schema(s => s
.Model(m => m.Id(p => p.ProductID));
.Data(
"Data"
);
.Total(
"Total"
);
.Errors(
"Errors"
))
.Transport(transport => t
.Read(r => r.Action(
"GetData"
,
"Controller"
,
new
{ IdClient = Model.Client.Id })
.Submit(
"onSubmit"
)))
And finally my javascript block
function
onSubmit (e) {
var
myData = e.data.created[0];
}
And the is the hic! myData like this
{
Id: 0,
ApplicationDate: Tue Apr 26 2016 00:00:00 GMT-0400 (heure d’été de l’Est)
}
Yes the quotes is missing in the output format. And the model is not valid. I set format on both DataSource.Shema.Model.Field.Format and Column.Bound.Format to "yyyy-MM-dd" and it still return JSON on incorrect format.
Does it possible to set Kendo to use ISO8601 instead of the JavasCrap Format ?
After I ran through the upgrader within Visual Studio 2019 to reference 2021.1.119 components I am all of a sudden seeing spurious <script> blocks rendered as inline html on certain (but not all) components and not on all views where various Kendo MVC components are referenced:
kendo.syncReady(function(){jQuery("#FiscalYearDropDown").kendoDropDownList({"change":onFiscalYearChange,"dataSource":{"transport":{"read":{"url":"/AssignedInvoices/GetFiscalYears"},"prefix":""},"schema":{"errors":"Errors"}},"dataTextField":"FiscalYear","dataValueField":"Fis
I had a dropdownlist in a page populated like so
@(Html.Kendo().DropDownList()
.Name(
"domain"
)
.DataTextField(
"DomainName"
)
.DataValueField(
"DomainName"
)
.DataSource(dataSource =>
dataSource.Read(read =>
read.Action(
"GetDomainNames"
,
"MinMax"
))
)
)
public
JsonResult GetDomainNames()
{
var dictDomains =
new
Dictionary<
string
,
string
>();
using
(var inoAutoEntities =
new
InoAutoEntities(InoAutoEntitiesHelper.GetEntityString(InoAutoEntitiesHelper.GetCredents())))
{
var localSettings = inoAutoEntities
.Settings
.Where(item => item.Machine ==
"."
)
.ToDictionary(item => item.Name);
if
(localSettings[
"UseAutomatedControlService"
].Value==
"True"
)
{
foreach
(var domain
in
inoAutoEntities.CartSideDomains.GroupBy(item => item.Domain).Select(item => item.Key))
{
dictDomains.Add(domain, domain);
}
}
else
{
var carts = inoAutoEntities.CartControls.Where(item => item.TypeControl == (
int
)ETypeControl.Owner).ToList();
foreach
(var cartControl
in
carts)
{
if
(!dictDomains.ContainsKey(cartControl.Domain))
{
dictDomains.Add(cartControl.Domain, cartControl.Domain);
}
}
}
}
var returnList = dictDomains
.Keys
.OrderBy(item => item)
.ToList();
returnList.Insert(0,
"All Domains"
);
var result = returnList.Select(item =>
new
DomainModel() {DomainName = item}).AsEnumerable();
return
Json(result,JsonRequestBehavior.AllowGet);
}
I wanted to move the dropdownlist to a toolbar but i see that the only way to do that is to use javascript to initialize
what is the syntax that would allow me to populate using a datasource that calls the controller action. I could not find information in the
documentation for toolbar or dropdownlist. any help would be appreciated
@(Html.Kendo().ToolBar()
.Name(
"ToolBar"
)
.Items(items =>
{
items.Add().Template(
"<div><label>Labels:</label><input id='labels' style='width: 150px;' /></div>"
).OverflowTemplate(
"<span></span>"
);
}
)
)
<script type=
"text/javascript"
>
$(document).ready(
function
() {
$(
"#labels"
).kendoDropDownList({
dataTextField:
"DomainName"
,
dataValueField:
"DomainName"
});
});
</script>
Hello, I am using dotnet MVC 6 (not core) and I have a need to only allow the KendoUI on some pages but not others. I am using the controls on a form built before we bought KendoUI, some forms were pre-built using the dotnet mvc scaffolding tool. Those forms do not need the KendoUI emitters, which normally would not be a problem except that when I run the project I am getting the following error in chrome:
Uncaught ReferenceError: kendo is not defined
And the following code is included for each control on the page:
kendo.syncReady(function(){jQuery("#First_Name").kendoTextBox({"value":"James"});});
I have tried removing the javascript references and that did not work, the code still gets emitted. I know why it is happening, because the javascript files are loaded at the bottom of the page, way after the above script tries to execute. I can't use deferred as I am not using the Kendo helpers on this page. Is there any other way to do this besides moving the kendo controls to the top of the page? And, if I have to move the controls to the top of the page, can I do that without moving the bootstrap and jquery script calls to the top as well (IE., are the kendo scripts dependent on JQuery or Bootstrap to be initialized first)?
Thanks in advance...