MVC wrapper and regular JavaScript Kendo grid together - asp.net-mvc

So I was trying to bind a complex object , a list, to the detail grid of the the Kendo grid. I understand that you can not do that, so what I did was grab the data and turn it into a JSON and use that as a data source for this grid I created. The grid is created like this
#(Html.Kendo().Grid(Model).Name("Access")
.Columns(columns =>
{
columns.Bound("ProjId").Width(220).Title("Project #");
})
//I tried
.DetailTemplate("<div id=DetailTemplate'></div>")
// I also tried
.ClientDetailTemplateId("<div id=DetailTemplate'></div>")
.Selectable()
.Events(events => events.DetailInit("initDetailGrid"))
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
I then have this in my script
<script type="text/javascript">
function initDetailGrid(e) {
//Hide the grid header
$(".k-grid tbody .k-grid .k-grid-header").hide();
var grid = e.sender;
//Get the data from the selected record
var currentDataItem = grid.dataItem(grid.select());
var newJsonObject = [];
for (var i = 0; i < currentDataItem.taskId.length; i++) {
var taskId = currentDataItem.taskId[i];
newJsonObject.push({
Id: objId,
Interval: currentDataItem.InternalExternal[taskId],
....
});
}
$("#DetailTemplate").kendoGrid({
columns: [
{field:"taskId", template:..stuff..},
{field: "Interval", template: .. stuff..}
],
dataSource: newJsonObject
});
}
</script>
So basically I want to use the $("#DetailTemplate") as the detail grid for the row but it not working and I do not know how to approach it.
EDIT
What I am trying to do is create a Kendo UI grid, via javascript, to use as the detail template for the parent Grid, which is created using the ASP-MVC helper.

It is not getting clear what you are trying to achieve. Did you check the hierarchy demo here?
Basically all you need to replace inside of it is to fill the dataSource directly instead of using transport configuration.
function detailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
//via the data option of the dataSource
data: e.data.NestedArrayFeild
},
scrollable: false,
sortable: true,
pageable: true,
columns: [
{ field: "OrderID", width: "70px" },
{ field: "ShipCountry", title:"Ship Country", width: "110px" },
{ field: "ShipAddress", title:"Ship Address" },
{ field: "ShipName", title: "Ship Name", width: "200px" }
]
});
}

Related

Variables are not accessible inside Action Url - kendo dropdown

I have a Kendo Html.Kendo().ComboBox() inside script tag in asp.net mvc.
var input = '#(Html.Kendo().ComboBox()
.Name(Html.NameFor(model => model.AttributeUnitValue).ToString())
.DataTextField("Description")
.DataValueField("CodeLovId")
.DataSource(datasource => datasource
.Read(read => read
.Action("GetCodesList", "LookupCode", new { area = "Core", codeType = unitCodeType, selectedValue = minAccValue })
.Type(HttpVerbs.Post)
)
).HtmlAttributes(new { style = "width:50%" }))'
Out side this input control I have two variables unitCodeType and minAccValue, which I am not able to access in Action() in the given code. They are showing error. Please check below screen shot
How can I fix this ?
You can pass server-side variables to the Action() method of the HtmlHelper. The Html helper is evaluated on the server i.e. based on the fluent configuration an initialization script is created and output along with an element used for the initialization of the component. So the JavaScript variable you are trying to pass is not available in the context when the Html Helper is evaluated.
You have two options - use server-side variables or initialize the ComboBox using JS:
#{
var someParam = 3;
}
<label for="products">HtmlHelper:</label>
#(Html.Kendo().ComboBox()
.Name("products")
.DataTextField("ProductName")
.DataValueField("ProductID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("RemoteDataSource_GetProducts", "DropDownList",new { myParam = #someParam});
});
})
.HtmlAttributes(new { style = "width: 200px;" })
)
<label for="products">JS initialization:</label>
<input id="products_js" style="width:200px;"/>
<script>
var someOtherParam = "test";
$("#products_js").kendoComboBox({
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: {
transport: {
read: {
dataType: "jsonp",
url: "https://demos.telerik.com/kendo-ui/service/Products",
data:{
myOtherParam:someOtherParam
}
}
}
}
});
If you inspect the Network tab in this example you will see the different parameters passed to the read endpoint.

kendo ui Clickable row

I created a Kendo UI Grid view and it displays data correctly , now what I am trying to achieve is that ; When i Click on a row I want to get the primary key of that row and use it elsewhere I tried many solution in net but I did not work. does anyone knows how to achieve this.
here is my code :
function FondsGrid() {
var sharedDataSource = new kendo.data.DataSource({
transport: {
read: {
url:
"http://localhost:...........",
dataType: "json"
}
},
pageSize: 20
});
var accountGrid = $("#grid-fonds").kendoGrid({
dataSource: sharedDataSource,
sortable: true,
pageable: false,
columns: [
{
field: "CodIsin",
title: " ",
template: '<span class="categ #= CodIsin #"></span>',
attributes: {
class: "text-center"
},
headerattributes: {
style: "text-align:center"
},
width: 35
},
{
field: "LIBELLEPDT",
title: "Nom du fonds",
template: '<div id="#: IdProduitSP #" class="title-fonds #:
IdProduitSP #" data-toggle="popover" ><span class="desc-
fonds">#: LibClassificationNiv2 #</span>#: LIBELLEPDT #
.
.
.
dataBound: function () {
var widthGrid = $('.k-grid-content').width();
$(".k-grid-header").width(widthGrid);
$(".title-fonds").popover({
trigger: 'hover',
html: true,
template: '<div class="popover HalfBaked" role="tooltip">
<div class="arrow"></div><h3 class="popover-header"></h3><div
class="popover-body"></div></div>',
content: function () {
return $('#popover-content').html();
}
});
}
}).getKendoGrid();
/* Initialisation */
$(document).ready(function ($) {
FondsGrid();
});
Your own answer is perfectly valid and is a good example of how you can use jquery to directly target the dom elements that kendo generates. This approach is always valuable when kendo does not offer the functionality you need.
However in this case, the grid widget offers the change event. You can set the grid to be 'selectable' and subscribe to the 'change' event which fires when one or more rows are selected:
selectable: "multiple, row",
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
// selectedDataItems contains all selected data items
}
Within the handler function, 'this' refers to the grid widget instance and calling the select() function on it returns the selected rows. From those rows, you can then retrieve the datasource items that are bound to them giving you access to the id and any other properties.
See here for more details: https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/events/change
This how I fixed It.
$("#grid-fonds").on("click", "td", function (e) {
var row = $(this).closest("tr");
var value = row.find("td:first").text();
console.log(value);
});

how to implement kendo autocomplete dropdown in MVC kendo treelist editor

Screen
Code
In this screen, we have used kendo treelist. I need to implement autocomplete dropdown in CODE column. How can i do that?
Try this
var ac = Html.Kendo()
.AutoComplete()
.Name("CodeAutoComplete")
.DataSource(ds =>
{
ds.Read(read =>
{
read.Url("youraction");
});
ds.ServerFiltering(true);
});
var treeGrid = Html.Kendo()
.TreeList<YourModel>()
.Name("SomeTreeList")
.Columns(columns =>
{
columns.Add().Field(t => t.YourProperty).Editor(ac.ToHtmlString());
});
I solve my above problem as per given below jquery code.
var input2 = jQuery('<input id="WEIGHT_UOM" value="' + e.model.WEIGHT_UOM + '">');
input2.appendTo($(".k-grid-edit-row").find("[data-container-for='WEIGHT_UOM']"))
//create AutoComplete UI component
$("#WEIGHT_UOM").kendoAutoComplete({
dataTextField: "ProjectDesc",
// template: '${ data.ProjectDesc }' + '<span style="display:none;> ${ data.ProjectDesc }</span>',
select: function (org1) {
var dataItem1 = this.dataItem(org1.item.index());
// model.set("field1", dataItem.field1);
e.model.set("WEIGHT_UOM", dataItem1.ProjectID);
},
dataSource: {
type: "jsonp",
serverFiltering: true,
transport: {
read: "#Url.Action("GetISOUnitAutoComp",
"DashBoard")",
}
}
});

How to set columns dynamically in Kendo template

How to set columns dynamically in Kendo template for kendo grid.In my kendo grid,columns are subject to change dynamically based on user preference.How to dynamically create Kendo Template?I am using Kendo JavaScript,I can switch to Kendo MVC if same thing i can achieve there.Is there any other approach to achieve this?
<script id="rowTemplate" type="text/x-kendo-template">
<tr class="k-master-row">
<td>
<div>#=column1#</div>
</td>
<td><span class="mydesign" title="column2#"</span></td>
<td>#column3#</td>
<td>#=column4#</td>
</tr>
</script>
Edit : In Kendo grid, we are dynamically setting the columns. Now issue is how do we set the dynamic width for content table and the header table. If it exceeds the max width how do we enable the horizontal scroll bar. Is there any approach to achieve this?
I'm not using kendo for MVC but I can still explain how to do this using regular kendo functions.
Basically, you can create a new kendo template instance by passing an html string to kendo.template. Then you can assign the new template instance to the grid's rowTemplate (or altRowTemplate) then call dataSource.read() to force a grid refresh.
You can generate your own html string or update an existing template in your page then use the jquery's html() to convert it into a string.
Ex:
var htmlTemplate = '';
if (userPreferences.likeRed) {
htmlTemplate ='<tr class="k-master-row"><td style="background-color:red">#column1#</td></tr>'
} else {
htmlTemplate ='<tr class="k-master-row"><td style="background-color:green">#column1#</td></tr>'
}
$("#grid").data("kendoGrid").rowTemplate = kendo.template(htmlTemplate);
$("#grid").data("kendoGrid").dataSource.read();
In order to format Kendo Grid column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?
Here are some of the usage samples below. You can easily generate different templates with the help of this approach.
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName)
.Title("Status Name")
.Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#")
.Width("55px");
...
Example I: In this example, Model is passed to the Javascript method by using "data" property and the model property is used in the "if" condition.
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>
Example II:
<script>
function Getvalue(value) {
// console.log(value);
if (value && value != null && value.indexOf("A") == 0)
return "<b style='color:red'>" + value + "</b>";
else
return "";
}
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: localDataSource,
columns: [
{
field: "FirstName",
title: "First Name", template: '#=Getvalue(FirstName)#'
}
],
});
});
</script>
Hope this helps...
This will work in ASP.NET MVC/Razor, if you prepare a collection of the dynamic columns definitions in advance, then put them in the view model for the cshtml. Then loop through the collection and insert the field name that will match the datasource, header title, desired width, etc...
$("#grid-quick").kendoGrid({
pageable: {
pageSizes: [10, 20, 50, 100]
},
sortable: { mode: "multiple" },
columns: [
#{
foreach (var col in Model.Columns)
{
#:{ field: "#col.Name.Replace(".","_")", width: "#col.Width" + "px" },
}
}
],
filterable: false,
dataSource: {
serverPaging: true,
serverSorting: true,
pageSize: 20,
type: 'aspnetmvc-ajax',
schema: {
data: "Data",
total: "Total",
model: {
fields: {
#{
foreach (var col in Model.Columns)
{
#: "#col.Name.Replace(".","_")" : { type: "string" },
}
}
}
}
},
transport: {
read: {
url: oVariables.baseURL + "Query/DynamicResults",
dataType: "json",
type: "post"
}
}
}
});

Linking rows/columns in Kendo Grid with different hper links

I am using Kendo Grid to show my search results.
Below is the code for Kendo Grid.
jQuery
$("#grid").kendoGrid({
dataSource: {
data: gridData,
schema: {
data: "Results"
},
pageSize: 20
},
height: 550,
sortable : true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: gridData.viewFields
});
$("#grid").kendoGrid('refresh');
I am adding data dynamically to gridData.viewFields.
Now i am trying to make rows clickable and navigate to display forms of items dynamically. I am struck here for a while. Any contribution is much appreciated.
Thank you.
First, you'll need to configure the grid to allow the row selection by setting the value for the selectable property:
$("#grid").kendoGrid({
selectable: "row"
//Other configuration value...
});
Then, you have to listen to the change event that will be triggered when the user will change the grid selection:
$("#grid").kendoGrid({
//Other configuration value...
change: function() {
var selectedRow = this.select();
//Insert your dynamic for logic here and user selectedRow to get the selected data
}
});

Resources