From Telerik to Kendo Treeview ItemDataBound - telerik

I am currently changing a website, where the company wants to change everything from Telerik to Kendo.
And I have now run into some troubles. In the BindTo method can have some mappings, and .ItemDataBound. And in that, you can set a Value. A full example is here:
#(Html.Kendo().TreeView()
.Name("MenuTree")
.Checkboxes(true)
.ExpandAll(true)
.DragAndDrop(false)
.Events(events => events.Select("onChecked"))
.BindTo(enumNames, mappings =>
{
mappings.For<string>(binding => binding.ItemDataBound((item, menuGroup) =>
{
item.Text = this.GlobalResource("EnergyLine", menuGroup);
MenuGroup result;
Enum.TryParse(menuGroup, true, out result);
item.Value = ((int)result).ToString(CultureInfo.InvariantCulture);
....
But Kendo does not have the attribute Value. What is the corresponding attribute for Kendo?

Try item.Id instead of item.Value.

Related

Using Kendo-UI grid for asp.net MVC, with multi-checkbox filtering, how do I configure data source for limiting options returned by the server?

I'm working with a Kendo-UI grid for asp.net MVC (version 2022.2.621.545) and I added multi-checkbox filtering to the columns. The grid items are pulled from the server using a configured ajax call to a controller action, and clicking on a filter button triggers another call to retrieve the full set of items in order to build the checkbox list. In some cases there are too many items returned and the grid appears to hang trying to determine the unique items for the checkbox list.
I was wondering if lazy loading can be configured for multi-checkbox filtering such that paging info is sent to the data source controller action. Alternatively, I've read that there may be a way to hold off on retrieving items for the filter until a minimal search string has been entered, with the search string being sent to the data source controller action.
I've looked at Kendo-UI documentation for multi-checkbox filtering options, but nothing has been abundantly clear that what I need to do is possible, especially within the asp.net MVC directives. I'm hoping someone can provide some guidance as to how to modify my grid setup to configure additional control for retrieving filter options. This is my current working code:
<div style="height:690px" id="warehouseGrid">
#(Html.Kendo().Grid<WarehouseModel>()
.Name("inventoryGrid")
.HtmlAttributes(new { style = "height:100%; width: 100%;" })
.Columns(columns =>
{
columns.Bound("InventoryLineItemID").Title("").Width(35).Filterable(false).ClientTemplate(
"<img src='https://cdn.host/show_detail.png' class='k-icon k-delete' height='45' width='45' onclick='ShowInventoryItemDetails(\"#= InventoryLineItemID #\")' onmouseover='' style='cursor: pointer;' title='Show Inventory Item Details' alt='Show Inventory Item Details' />"
);
foreach (WarehouseField col in fields)
{
if (!string.IsNullOrEmpty(col.Template))
{
columns.Bound(col.PropertyName).Title(col.Title).Width(col.Width).Filterable(false).ClientTemplate(col.Template);
}
else
{
columns.Bound(col.PropertyName).Title(col.Title).Width(col.Width).Filterable(ftb => ftb.Multi(true).Search(true));
}
}
})
.Pageable(pager => pager.PageSizes(new[] { 10, 20, 50, 100 }))
.Excel(excel => excel
.AllPages(true)
)
.ToolBar(
toolbar =>
{
toolbar.Template(#<text>
#ToolbarTemplate()
</text>);
}
)
.Events(e => e.DataBinding(#<text>function(e) { onDataBinding(this) }</text>))
.Events(e => e.DataBound(#<text>function(e) { onDataBound(this) }</text>))
.Resizable(r => r.Columns(true))
.ColumnResizeHandleWidth(5)
.Scrollable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Read(read => read.Action("GetInventory", "Warehouse", new { area = "Rest" }).Data("additionalData"))
)
)
</div>

Post kendo grid values

Below is the Kendo grid
#(Html.Kendo().Grid<CS.Web.Models.People.GroupDetailModel>()
.Name("Grid")
.Events(e => e.DataBound("LineItems_Databound"))
.HtmlAttributes(new { style = "overflow:hidden;", #class = "normalgrid" })
.Columns(columns =>
{
columns.Bound(p => p.GroupID).Hidden();
columns.Bound(p => p.GroupName).Title("Group Name").Width(30);
columns.Bound(p => p.Department).Title("Department Name").Width(30);
columns.Bound(p => p.IsBlindSettingsEnable).Title("Blind Group")
.ClientTemplate("<input type=\"checkbox\" #= IsBlindSettingsEnable ? \"checked=checked\": \"\" # enabled=\"enabled\" />")
.Width(30);
columns.Bound("Department").Title("Remove")
.ClientTemplate("<a href='javascript:void(0)' Title='Remove' onclick='return removeUserGroupRelation(+#=GroupID#+);'> <img alt='Remove' src='" + #Url.Content("~/Content/Images/delete_icon.png") + "' /></a>")
.Width(30);
})
.Sortable()
.Scrollable(scrollable => scrollable.Virtual(false))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("getAssignedGroups", "People")
.Data("setRoutesValues")
)
//new { MerchantId = ViewBag.MerchantId, StartDate = Model.StartDate, EndDate = Model.EndDate }
)
.TableHtmlAttributes(new { #class = "grid_1" })
)
Below is the javascript code
var userID = '#ViewBag.UserID'
$.ajax({
url: '#Url.Action("SaveGroupsUserDetails")',
type: "POST",
dataType: "json",
data: { models: kendo.stringify($("#Grid").data("kendoGrid").dataSource.view()), UserID: userID },
success: function (result) {
}
});
Here in my kendo grid there is checkbox column.When i check or uncheck checkbox at CLIENT sied(in browser).And Do post via give javascript $.ajax post,it will not post the values of checkboxes which I have changed on client browser,it shows the values which it was binded from server side.
so,my question is to I want updated values to post on server which are modified on client browser.
I shall be very thankfull if you provide me answer.
You should just update your datasource on checkbox checked :
...
.ClientTemplate("<input type=\"checkbox\" #= IsBlindSettingsEnable ? \"checked=checked\": \"\" # enabled=\"enabled\" onclick='setChecked(this)' />")
...
function setChecked(cb) {
var row = $(cb).closest("tr");
var item = grid.dataItem(row);
item.IsBlindSettingsEnable = cb.checked;
}
and now your datasource is synced with the view
I believe this is because your looking at the actual value of the dataSource and not the grid itself. Your grid is non-editable. You are manually throwing the inputs into your grid and these will not effect the dataSource.
You can take two approaches do this kind of update.
You can leave the grid the way you have it set up and handle this update solely though Java Script.
To do this you will need to look up all the dataItems you need to update manually with JQuery.
You can lookup all of your check boxes with in that grid that are check, then get the relevant dataItem manually. Here is a short example showing how to get a dataItem from a row in the grid.
//checkbox is a JQuery object referencing one of your checkboxes
var row = $(checkbox).closest("tr");
var grid = $("#grid").data("kendoGrid");
var data = grid.dataItem(row);
Once you have all of your dataItems that are relevant you can then post your update. You would then have to reload your grid to get the updated status of these items.
Overall this is not the preferred way to do this kind of update with a kendo grid.
I suggest this second method.
This is the site where I will be pulling examples from: http://demos.telerik.com/aspnet-mvc/grid/editing
First you will need to make your kendo grid editable .Editable(editable => editable.Mode(GridEditMode.InCell)). You will not need the custom template that adds the checkbox anymore. It will automatically add them when you are editing your grid now.
You will need to then set the datasource to have an update function and have your server expect this update.
Your dataSource binding
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Read("Editing_Read", "Grid")
.Update("Editing_Update", "Grid")
)
And your server side code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
{
if (products != null && ModelState.IsValid)
{
foreach (var product in products)
{
productService.Update(product);
}
}
return Json(products.ToDataSourceResult(request, ModelState));
}
By returning this Json object your grid will auto update to the new values. This is the preferred way to edit a grid.

Kendo UI ASP.Net MVC ForeignKey column DataSource in InCell Edit mode

I have Kendo Grid and a ForeignKey column on a page. ForeignKey column is populated using ViewData as described below.
column.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName");
The Grid is editable in batch(InCell) mode as show below...
.Editable(editable => editable.Mode(GridEditMode.InCell)
I want to modify collection of ProductID column in the grid after page is loaded based on value selected on other drop-down defined outside of the Grid.
How can I achieve that? Can I do it using jQuery?
Similar example I found here...
http://www.telerik.com/community/forums/aspnet-mvc/grid/cascading-dropdowns-in-grid-edit---foreignkey-columns.aspx
Thanks.
I figured out how to filter the Product drop-down using an EditorTemplate for the foreign key column.
Here is my column definition for the Product.
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName").EditorTemplateName("ProductIDEditor");
Here is the editor template for Product, ProductIDEditor.cshtml
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.OptionLabel("Select a value...")
.DataTextField("ProdName")
.DataValueField("ID")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("FilterProducts", "Home").Data("filterProducts"))
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
In my main VIEW Index.cshtml, I added filterProducts JavaScript handler, that passes JSON object for productID to controller.
function filterChargeTypes()
{
return {
productID: $("#ProductID").val()
};
}
Here is the controller that listens to filtering event...
public ActionResult FilterProducts(string productID)
{
// do your filtereing based on productID.
}
FilterProducts will be called every time when user hits the drop-down to get filtered value.
You don't need the Editor Template. It will bind to a dropdown without it. You can use this, like you had, just minus the template:
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName")
or
c.ForeignKey(x => x.ProductID, (System.Collections.IEnumerable)ViewData["products"], dataFieldValue: "ID", dataFieldText: "ProdName")
And for filtering, you can just invoke .Filterable() on the grid.

How to bind a telerik mvc dropdown using javascript

I have an application with two telerik mvc drop-downs - region and country. I need to populate the country drop-down using an ASMX Web Service every time the region drop-down change. In other words I need to pass a parameter to the web service and a way to call the bind method form the client. This is what I have but it's not working.
#(Html.Telerik().DropDownList()
.Name("RegionDDL")
.BindTo(new SelectList(Model, "value", "value"))
.ClientEvents(events => events.OnChange("onChange"))
)
#(Html.Telerik().DropDownList()
.Name("SeasonDDL")
.ClientEvents(events => events
.OnDataBinding("onDropDownListDataBinding")
)
.DataBinding(dataBinding => dataBinding
.WebService().Select("~/country.svc/GetSeasonDropDownItems"))
)
Now the scripts
<script type="text/javascript">
var RegionDDLv;
function onChange() {
//Get the region
RegionDDLv = $("#RegionDDL").data("tDropDownList").value();
var countryDDLv = $("#countryDDL").data("tDropDownList");
countryDDLv.dataBind();//THIS IS NOT WORKING
}
function onDropDownListDataBinding(e) {
e.data = { region: RegionDDLv };
}
</script>
Thanks
After some research, I found the answerer here
http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-combobox-client-api-and-events.html
It is
countryDDLv.reload();
try
SeasonDDLv.rebind();
instead of
SeasonDDLv.dataBind();

Telerik RadGrid CustomSorting without hitting database?

I tried to post on Telerik forum, but now each time I try to open my thread, I get
"Oops...
It seems there was a problem with our server."
So I posted this question here.
I am pretty new to Telerik and RadGrid. I am trying to modify existing project because client needs custom sorting. There is a data field which may contain numbers or text so it is a string type but sometimes it has to be sorted as numbers. So I went to this link:
http://demos.telerik.com/aspnet-ajax/grid/examples/programming/sort/defaultcs.aspx
and
http://www.telerik.com/help/aspnet-ajax/grdapplycustomsortcriteria.html
The example says:
"With custom sorting turned on, RadGrid will display the sorting icons but it will not actually sort the data."
but it seems it is not enough to add AllowCustomSorting to disable default sorting.
When implementing SortCommand, I noticed that I have to do
e.Canceled = true;
because else default sorting occurs. Why this is not mentioned in the documentation nor example?
But the main question is - inside of SortCommand my RadGrid already has all items loaded. So is there any way to sort them to avoid hitting database? I tried accessing various Items properties of both "object source, GridSortCommandEventArgs e", but all Items are read-only, so I cannot sort them and attach back to the RadGrid.
Thanks for any ideas.
You can set the sortExpression in the OnSelecting event of the objectDatasource and use it in the SelectMethod.
protected void odsGridData_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["filterExpression"] = grdMyTasks.MasterTableView.FilterExpression;
//Set the Sort Expression and use this in the Get method
e.InputParameters["sortExpression"] = grdMyTasks.MasterTableView.SortExpressions.GetSortString();
e.Arguments.StartRowIndex = grdMyTasks.CurrentPageIndex;
e.Arguments.MaximumRows = grdMyTasks.PageSize;
}
This way you can perform custom sort and pass on the data to the RadGrid.
Hope this helps.
Here is an example of some code I use that does not hit the database. I'm using MVC 3 with the Razor view engine. Notice the Ajax binding. Don't forget to add using Telerik.Web.Mvc.UI and annotate the "Post" methods in your controller with [GridResult] and to return GridModel to get the Json resultset.
using Telerik.Web.Mvc;
[GridAction]
public ActionResult AjaxGridSelect()
{
return View(new GridModel(db.lm_m_category));
}
Here is the index.cshtml (razor engine), the key is the Ajax binding.
#model IEnumerable<LinkManagerAdmin.Dal.lm_r_category>
#using Telerik.Web.Mvc.UI
#(Html.Telerik().Grid(Model)
.Name("Grid")
.DataKeys(keys => keys.Add(c => c.category_id ))
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("AjaxGridSelect", "CategoryTree")
.Insert("GridInsert", "CategoryTree", new { GridEditMode.PopUp, GridButtonType.ImageAndText })
.Update("GridUpdate", "CategoryTree", new { GridEditMode.InLine, GridButtonType.ImageAndText })
.Delete("GridDelete", "CategoryTree", new { GridEditMode.InLine, GridButtonType.ImageAndText }))
.Columns(columns =>
{
columns.Bound(p => p.category_name).Width(150);
columns.Bound(p => p.status_cd).Width(100);
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.ImageAndText);
commands.Delete().ButtonType(GridButtonType.ImageAndText);
}).Width(180).Title("Commands");
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Pageable(paging => paging.PageSize(50)
.Style(GridPagerStyles.NextPreviousAndNumeric)
.Position(GridPagerPosition.Bottom))
.Sortable(o => o.OrderBy(sortcol =>
{
sortcol.Add(a => a.category_name);
sortcol.Add(a => a.add_date);
})
.Filterable()
.Groupable()
.Selectable())

Resources