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

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.

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>

Kendo UI DropDownListFor Set SelectedValue

I'm working with Kendo UI on an MVC application. We have a grid and when the user opens the row for editing we have a dropDownList that holds company names. I'm trying to get the DDL to default to the company name that's pertinent to the row.
Here's the column code:
columns.Bound(e => e.company_business_name).Width(220).Title("Company")
.EditorTemplateName("CompanyName");
and here's the editorTemplate code:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.BindTo((System.Collections.IEnumerable)ViewData["Companies"])
)
and the method that fills the DDL:
private void PopulateCompanies()
{
var companyList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(Session["Companies"] as string))
{
companyList = (List<SelectListItem>)Session["Companies"];
}
else
{
companyList = new DataAccess().GetCompanies(CurrentSettings.getUser().userId);
CacheCompanies(companyList);
}
ViewData["Companies"] = companyList;
}
EDIT:
Updated the code. The DDL still populates but I'm still not getting the selected value when I click "edit" on the grid row. Feel like I'm close here, help!
The problem is that your Editor Template's model is your entire model, not the company_business_name property (Very bad name for a property, by the way. You need to follow the standard naming conventions).
You don't even need to fill the drop down list.
Your Editor Template should be something like this:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(x =>
x.Read(read => read.Action("GetCompanies", "AddEntry"))
)
)

From Telerik to Kendo Treeview ItemDataBound

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.

Telerik MVC export to excel

I was using Telerik Grid in MVC3 project. In this I have to use the functionality of exporting. In order to export data, I need all the currently available items should be exported as excel format.
I done with exporting. But I need to export all the data currently are available in the grid. It means when filtering Not only the current page's data, It should export all the filtered data's.
I have done something like this: But its not exporting only the filtered data's but all the data's in the grid.
View Code
#(Html.Telerik().Grid(Model)
.Name("Grid")
.ToolBar(commands => commands
.Custom()
.HtmlAttributes(new { id = "export" })
.Text("Export to Excel")
.Action("ExportExcel", "Grid",
new { page = 1, orderBy = "~", filter = "~" }))
.DataKeys(keys =>
{
keys.Add(Id => Id.Itemid);
})
Action Method in my Controller
public ActionResult ExportExcel(int page, string orderBy, string filter)
{
IEnumerable orders = GetItems()
.AsQueryable()
.ToGridModel(page, int.MaxValue, orderBy,
string.Empty, filter).Data;
Is there any way that I can do with this. Please help for this.
Thanks,
The following example shows how to export only the relevant data: http://demos.telerik.com/aspnet-mvc/grid/customcommand
There is also a code library project which shows how to export the grid data to Excel: http://www.telerik.com/support/kb/aspnet-mvc/grid/export-to-excel.aspx

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