I am trying to get a Kendo grid to display a list of values using a for loop in the client template except it keeps crashing the grid when I try it. The grid is below:
#( Html.Kendo().Grid<ProjectXMVC3.ViewModel.PersonnelIndexViewModel>()
.Name("Personnel")
.Columns(columns =>
{
columns.Bound(o => o.AssetId).Hidden();
columns.Bound(o => o.Num).Hidden();
columns.Bound(o => o.Name).Width(150);
columns.Bound(o => o.Email).Width(200);
columns.Bound(o => o.AssetSubType).ClientTemplate("# var j = AssetSubType.length; for(var i = 0; i < j; i++){# #: AssetSubType[i] # #}#" );
columns.Bound(o => o.DateBirth).Format("{0:d}").Width(100);
columns.Bound(o => o.Country).Title("Nationality").Width(200);
columns.Command(com => {
com.Custom("Details").Click("onPersonSelected");
com.Custom("Block").Click("onBlocked");
});
})
.DataSource(d => d
.Ajax()
.Model(model => model.Id(p => p.AssetId))
.Read(read => read.Action("Read_Personnel", "Personnel"))
)
)
I can get an individual AssetSubType to display using an if statement but as soon as I put in the loop it throws a double six and gives up. AssetSubType is an IEnumerable of the ViewModel.
I've taken out any sorting, filtering etc. I'm new to Kendo as well.
Any assistance is much appreciated...
I had the same problem, and solved it with something like this:
first add a new script and move the for loop inside it:
<script type="text/javascript">
function printAssetSubType(AssetSubType) {
var result = "";
var j = AssetSubType.length;
for(var i = 0; i < j; i++) {
result += AssetSubType[i];
}
return result;
}
</script>
then refer to this script from the column itself:
columns.Bound(o => o.AssetSubType).ClientTemplate("#=printAssetSubType(AssetSubType)#");
You can also add a new field in your PersonnelIndexViewModel class, and prepare the string you want to display server-side, in your controller.
Controller:
myViewModel.AssetSubTypeString = String.Join(", ", myAssetSubTypes);
View:
columns.Bound(o => o.AssetSubTypeString);
Related
I have a kendo grid and need to get a querystring value. See below code.
Browser Url = http://blahblah/blah/36?EvaluationCriteriaGrid-mode=edit&chiefEvalCriteriaId=110
UI.cshtml
#(Html.Kendo().Grid(Model.ChiefEvaluationCriteriaList.AsEnumerable())
.Name("EvaluationCriteriaGrid")
.Columns(columns =>
{
columns.Bound(p => p.EvaluationCriteriaName);
columns.Bound(p => p.MinScore).Width(100).Title("Min Score").Format("{0:0}");
columns.Bound(p => p.MaxScoreDisplay).Width(100).Title("Max Score");
columns.Command(command => { command.Edit(); }).Width(180).Title("Action");
})
.CellAction(cell =>
{
if (cell.Column.Title == "Action")
{
if (cell.DataItem.EvaluationResultID ==
ServiceProxy.Model.DomainConstants.EVALUATION_RESULT_APPROVED)
{
cell.HtmlAttributes["style"] = "display:none;";
}
}
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Server()
.Model(model => model.Id(c => c.ChiefEvaluationCriteriaID))
.Read("EvaluationQuestionnaire", "EvaluationCriteria", new { area = "Proposal", Id = Model.SolicitationDetails.SolicitationID })
.Update("EditEvaluationCriteria", "EvaluationCriteria", new { area = "Proposal", Id = Model.SolicitationDetails.SolicitationID })
)
)
Controller.cs
[HttpPost]
public ActionResult EditEvaluationCriteria( int Id, int chiefEvalCriteriaId, int maxScoreDisplay, int minScoreDisplay = 0 )
{
if (ModelState.IsValid)
{
Do something
}
return view
}
Thank you for the support
I am using the Kendo Sortable to enable drag-and-drop reordering of rows in a grid (similar to this example. My grid also allows inline editing of rows.
The same datasource Update method gets called in either of these cases: Clicking update after an inline edit, or drag-and-dropping a row to reorder.
Is it possible to have the drag-and-drop reorder call a different datasource Update method?
Here is the grid code:
#(Html.Kendo().Grid<BSS.WebMvc.ViewModels.SuggestionViewModel>()
.Name("gridSuggestions")
.Columns(columns =>
{
columns.Bound(p => p.DisplayOrder).Hidden(true);
columns.Bound(p => p.Item);
columns.Bound(p => p.Quantity);
columns.Command(command => { command.Edit(); command.Destroy(); });
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Suggestion"))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("gridSuggestions_error_handler"))
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p => p.DisplayOrder).DefaultValue(0);
model.Field(p => p.Item).DefaultValue(new BSS.WebMvc.ViewModels.ResultEntryViewModel());
model.Field(p => p.Quantity).DefaultValue(1);
})
.Create(update => update.Action("Suggestions_Create", "Items", new { parentItemId = Model.ID }))
.Read(read => read.Action("Suggestions_Read", "Items", new { id = Model.ID }))
.Update(update => update.Action("Suggestions_Update", "Items", new { parentItemId = Model.ID }))
.Destroy(update => update.Action("Suggestions_Delete", "Items", new { parentItemId = Model.ID }))
.ServerOperation(false)
.Sort(s => s.Add(m => m.DisplayOrder))
)
.Events(events => events.DataBound("gridSuggestions_dataBound").Edit("gridSuggestionEditOrCreate").SaveChanges("gridSuggestionSaveChanges").Cancel("gridSuggestionCancel").Save("gridSuggestionSave"))
)
And the sortable code with the relevant javascript function:
#(Html.Kendo().Sortable()
.Name("gridSuggestionSortable")
.For("#gridSuggestions")
.Filter("table > tbody > tr:not(.k-grid-edit-row):not(.blockDragDuringEdit):not(.preventDrag):not(.k-detail-row)")
.Cursor("move")
.HintHandler("hint")
.Axis(SortableAxis.Y)
.PlaceholderHandler("placeholder")
.ContainerSelector("#gridSuggestions tbody")
.Events(events => events.Change("onGridSuggestionsOrderChange"))
)
<script>
function onGridSuggestionsOrderChange(e) {
let grid = e.sender.element.data("kendoGrid"),
oldIndex = e.oldIndex,
newIndex = e.newIndex,
view = grid.dataSource.view(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
dataItem.DisplayOrder = newIndex;
dataItem.dirty = true;
if (oldIndex < newIndex) {
for (let i = oldIndex + 1; i <= newIndex; i++) {
view[i].DisplayOrder--;
view[i].dirty = true;
}
} else {
for (let i = oldIndex - 1; i >= newIndex; i--) {
view[i].DisplayOrder++;
view[i].dirty = true;
}
}
grid.dataSource.sync();
}
</script>
You could call a different method in the change handler:
function onGridSuggestionsOrderChange(e) {
...
dataItem.DisplayOrder = newIndex;
const updated = [dataItem.toJSON()];
if (oldIndex < newIndex) {
for (let i = oldIndex + 1; i <= newIndex; i++) {
view[i].DisplayOrder--;
updated.push(view[i].toJSON());
}
} else {
for (let i = oldIndex - 1; i >= newIndex; i--) {
view[i].DisplayOrder++;
updated.push(view[i].toJSON());
}
}
$.ajax({
type: "POST",
url: REORDER_UPDATE_URL,
contentType: 'application/json',
data: JSON.stringify(updated)
});
}
I've got a Kendo Grid in which one of the columns is passed a List<string>. Right now it displays [object Object], but I'd like it to display the list of strings separated by commas. I found this answer: Kendo Grid: How display List<string> in one cell?
But the solutions proposed don't work for me. It just prevents the grid from rendering at all.
This displays [object Object] in the column:
#(Html.Kendo().Grid<Models.MyConfigModel>
()
.Name("MyListGrid")
.Columns(columns =>
{
columns.Bound(p => p.myList).Title("My List").HeaderHtmlAttributes(new { style = "overflow: visible; white-space: normal;text-align:center" }).Width(150);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Read(read => read.Action("MyListGrid_Read", Model.ControllerName))
.ServerOperation(false).Model(model => model.Id(p => p.MyID)))
This causes nothing to be displayed:
#(Html.Kendo().Grid<Models.MyConfigModel>
()
.Name("MyListGrid")
.Columns(columns =>
{
columns.Bound(p => p.myList).Title("My List").ClientTemplate("# =iterate(myList) #").HeaderHtmlAttributes(new { style = "overflow: visible; white-space: normal;text-align:center" }).Width(150);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Read(read => read.Action("MyListGrid_Read", Model.ControllerName))
.ServerOperation(false).Model(model => model.Id(p => p.MyID)))
Here's my iterate function:
function iterate(object) {
if (object !== null && object.length > 0) {
for (var x = 0; x < object.length; x++) {
html += object[x];
html += ", ";
}
html = html.slice(0, -2);
return html;
}
}
Here's how I would do it:
Grid:
columns.Template(p => { }).Title("My List").ClientTemplate("#= iterate(data) #").HeaderHtmlAttributes(new { style = "overflow: visible; white-space: normal;text-align:center" }).Width(150);
Javascript:
function iterate(data) {
if (data.myList!== null && data.myList.length > 0) {
for (var x = 0; x < data.myList.length; x++) {
html += data.myList[x];
html += ", ";
}
html = html.slice(0, -2);
return html;
}
return "";
}
I have a Kendo UI Grid which allows for multiply row selection using check boxes located on each row.
As I select each item, there is a delay before the row is highlighted.
The selection becomes progressively slow and eventually unresponsive.
I suspect the adding/removal of the classes in the function "updateNameList" is the culprit, but do not know of another way of achieving this.
Any help appreciated, thanks.
#(Html.Kendo().Grid<MyItems>()
.Name("MyItems")
.DataSource(
datasource => datasource
.Ajax()
.ServerOperation(false)
.Read(read => read.Action("GetMyItems", "ItemMgr", new { id = new Guid("E1CB204D-74CD-4995-A14F-F5A6FFFCB2E7"), accountid = ViewBag.AccountId }))
.Model(m => m.Id(mx => mx.ItemId))
)
.Columns(columns =>
{
columns.Bound(c => c.Name).Template(#<text></text>).ClientTemplate("<input type='checkbox' class='name-select-chk' data-target='#= Name #' />").HeaderTemplate("").Width(20);
columns.Bound(c => c.Name).Width(60).Title("Name");
columns.Bound(c => c.Status).Width(60).Title("Status");
.Filterable()
.Sortable()
.Selectable(select => select.Mode(GridSelectionMode.Single))
.Events(
e=>e.Change("selection_change")
)
)
function selection_change(arg) {
var selectedItem = this.dataItem(this.select());
if ($.inArray(selectedItem.Name, selectedNames) >= 0) {
selectedNames.splice(selectedNames.indexOf(selectedItem.Name), 1);
} else {
selectedNames[selectedNames.length] = selectedItem.Name;
}
updateNameList(arg);
}
function updateNameList(e) {
var Names = "";
for (i = 0; i < selectedNames.length; i++) {
Names += selectedNames[i];
if (i < selectedNames.length-1) {
Names += ", ";
}
}
$("#MyItems tr").each(function (index) {
$(this).removeClass("k-state-selected");
$(this).find("input").prop('checked', false);
for (i = 0; i < selectedNames.length; i++) {
if ($(':nth-child(2)', this)[0].innerHTML == selectedNames[i]) {
$(this).addClass("k-state-selected");
$(this).find("input").prop('checked', true);
}
}
});
}
I have been using inline deletion for Kendo Grid, but I need to check the conditions and then delete the rows.
#(Html.Kendo().Grid<DocumentSearchViewModel>()
.Name("documentListGrid")
.Columns(columns =>
{
columns.Bound(model => model.AgentID).Title("Agent Code").Width("15%");
columns.Bound(model => model.DocumentSecurityID).ClientTemplate("#if(data.AllowToView==1)" +
"{ #<a class='lnkDocument' href='" + Url.Action("Download", "Document", new { fileName = "#=ScanFile#", fileLocation = "#=VC01#", batchTime = "#=BatchTime#", documentNumber = "#=CaseID#" }) + "' target='documentViewer'>#=data.BatchDescription#</a>#" +
" " + " }" +
"else{#<a class='disable-link' onclick='return Response();'>#=data.BatchDescription#</a> #}#").Title("Description").Width("30%");
columns.Bound(model => model.CaseID).Width("10%").Title("Case#");
columns.Bound(model => model.DocumentGroupID).Width("15%").Title("Group ID");
columns.Bound(model => model.BatchNumber).Width("10%").Title("Batch#");
columns.Bound(model => model.CreatedDate).Width("10%").Format(UI.DocumentSearchDateFormat).Title("Created Date");
columns.Command(command => command.Custom("Remove").Click("deleteRow"));
columns.Bound(model => model.DocSystemID).Visible(false);
})
.Pageable()
.Sortable(sortable => sortable.AllowUnsort(false))
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Model(model => model.Id(p => p.CaseID))
.Read(read => read.Action(WorkflowControllers.Document.ActionNames.GetDocumentList, WorkflowControllers.Document.Name, new { caseId = #Model.CaseID }))
.Events(ev => ev.Change("OnGridChange"))
).AutoBind(true).Events(events => events.DataBound("DisplayDocument"))
)
Calling javascript function which will call a Controller method using Ajax Call:
function deleteRow(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var grid = $("#documentListGrid").data("kendoGrid");
if (confirm("Are you sure you want to delete the selected record(s)?")) {
grid.removeRow($(e.target).closest("tr"));
} else {
// cancel button is clicked
}
}
How do I get the row's value and check the conditions?
$('#Grid').click(function () {
var gview = $(this).data("kendoGrid");
var selectedItem = gview.dataItem(gview.select());
var Guid = selectedItem.YourPropertName;
})
selectedItem will have all the properties of your model