kendo grid error with sorting - kendo-ui

I have the next
#(Html.Kendo().Grid<Corporativo.Model.SolicitudProductoVM>()
.Name("SolicitudesProducto")
.Columns(columns =>
{
columns.Bound(e => e.Consecutivo).Width(20).Title("CĂ“DIGO");
columns.Bound(e => e.Desc_Cliente).Width(80).Groupable(false).Title("CLIENTE");
columns.Bound(e => e.Fecha).Width(40).Groupable(false).Title("FECHA");
columns.Bound(e => e.Imp_Total).Width(40).Groupable(false).Title("IMP. TOTAL");
})
.Filterable()
.Pageable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetAllSolicitudesJSON", "CrmProductRequest", null))
)
)
with the next error...
Cannot find a public property of primitive type to sort by.
Ideas???

I have this error with Kendo UI and I did not have sorting used in my view. For me it I found an issue with the view model, I had used a view model to stop an different issue with EF objects causing circular errors. If this is still an issue and you use view models try setting the attributes with full getter and setters.
I had my view model properties declared like this: *
public int OrderID;
I and I changed them to this to get Kendo .ToDataSource() to work:
public int OrderID
{
get;
set;
}
*Other syntax issues with these properties could also cause this error.
This is the article that explains how to get rid of circular references that indirectly helped me come to this conclusion. I hope that this may still be helpful to someone who stumbled onto this question like I did.

Related

Kendo UI Grid dropdown with Foreign key

I should have asked this question on the Telerik forum but having browsed through many answers there, with due respect to Telerik, I feel it will be futile and I can expect better and quicker answers here. So here I go:
I am using Kendo UI Grid control and displaying the values in an editable dropdownlist cell.But that has taken away the in built filtering capability as it is not provided out of the box. Now I am stuck on the only way to achieve this which is using foreign keys; http://demos.telerik.com/aspnet-mvc/grid/foreignkeycolumn
There are some bits missing in the example like the PopulateCategories() function and what code to put in the MVC EditorTemplate.
Has anyone tried and successfully able to display the filters? I can provide my code but I think thats not part of the question as there is nothing wrong in the code. What I am asking is how I can achieve filtering with dropdownlist templates using the solution provided by Telerik.
Hope it may help someone.The following bits are missing from the example as provided in the link above (I have used my code to convey the missing bits):
First
Instead of:
columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "CategoryID", "CategoryName")
.Title("Category").Width(150)
Use EditorTemplateName property too:
columns.ForeignKey(p => p.Region.RegionId, (System.Collections.IEnumerable)ViewData["Regions"], "RegionId", "RegionName").Title("Region").EditorTemplateName("RegionsTemplate");
Second
Keep using the complex model otherwise the Add New Record functionality would not work:
So instead of
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.ProductID).Editable(false);
model.Field(p => p.CategoryID).DefaultValue(1);
})
Use both the Foreign key model and the complex model:
.Model(model => {
model.Id(p => p.FunctionLevelRegionMappingId);
model.Field(p => p.FunctionLevelRegionMappingId).Editable(false);
model.Field(p => p.Region.RegionId).DefaultValue(1);
model.Field(p => p.Region).DefaultValue(
ViewData["DefaultRegion"] as GlobalLossAnalysisTool.Web.Areas.Administration.Models.RegionDto);
})
Third
In the example ProductViewModel is missing. This can be referred from http://demos.telerik.com/aspnet-mvc/grid/editing-custom. There is no change to this model.
Fourth
Changes to template:
The templates are missing in the example but can in inferred from the link http://demos.telerik.com/aspnet-mvc/grid/editing-custom. Change the template from :
#model Kendo.Mvc.Examples.Models.CategoryViewModel
#(Html.Kendo().DropDownListFor(m => m)
.DataValueField("CategoryID")
.DataTextField("CategoryName")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
To:
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownListFor(m => m)
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"]))

Kendo UI Grid returns JSON to browser (using MVC)

I've recently purchased a Kendo subscription, I'm having trouble getting an AJAX bound grid to operate as expected, hoping someone here can help.
I have followed the Kendo docs tutorial # http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
and could get the AJAX binding working nicely.
I've tried to now implement it into an existing MVC solution, and whenever I click the New or Edit command button, I get a string of JSON returned to the browser. Similiar to issue (JSON data to KENDO UI Grid ASP.NET MVC 4) But the answer in that problem didn't work for me.
Here is my Controller code...
public ActionResult Index()
{
// non-important code removed here //
var viewModel = newReferenceViewModel();
ViewBag.TradeReferences = TradeReferenceWorker.Get(applicationId);
return View(viewModel);
}
public ActionResult TradeReferences_Read([DataSourceRequest]DataSourceRequest request)
{
var applicationId = GetCurrentApplicationId();
DataSourceResult result = TradeReferenceWorker.Get(applicationId).ToDataSourceResult(request);
return Json(result, "text/x-json", JsonRequestBehavior.AllowGet);
}
And the View ....
#(Html.Kendo().Grid((IEnumerable<TradeReference>)ViewBag.TradeReferences)
.Name("gridTradeReference")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(tradeReference => tradeReference.TradeReferenceId);
model.Field(tradeReference => tradeReference.TradeReferenceId).Editable(false);
})
.Read(read => read.Action("TradeReferences_Read", "References"))
.Create(create => create.Action("TradeReference_Create", "References"))
.Update(update => update.Action("TradeReference_Update", "References"))
.Destroy(destroy => destroy.Action("TradeReference_Destroy", "References"))
)
.Columns(columns =>
{
columns.Bound(tref => tref.TradeReferenceId).Visible(false);
columns.Bound(tref => tref.Name);
columns.Bound(tref => tref.Phone);
columns.Command(commands =>
{
commands.Edit();
commands.Destroy();
}).Title("").Width(200);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Sortable()
)
So to sum up... the Grid will load perfectly the first time. I haven't wired up anything on the Edit / Delete actions, just trying to get Create operational. Clicking Add New, or even Edit for that matter will make the browser simply display Json to the screen.
It is hopefully something simple - thanks in advance
Solved it - the problem was the kendo js files were not being referenced correctly.
In my particular case, the bundling wasn't done 100% correctly so the Kendo javascript files were never getting included in the page.
They must also appear in a certain order, as described in the troubleshooting guide http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/troubleshooting

Kendo UI ASP.NET MVC grid datasource filters value is null

I am trying to dynamically add grid filters in my view using the html helper via datasource configuration, like this example from the kendo documentation:
#(Html.Kendo().Grid<Product>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Products_Read", "Home"))
.Filter(filters =>
{
if (someCondition){
// Show products whose ProductName property contains "C"
filters.Add(product => product.ProductName).Contains("C");
// and UnitsInStock is greater than 10
filters.Add(product => product.UnitsInStock).IsGreaterThan(10);
}
})
)
)
The filters are added, but the filterdescriptor.Value in each case is always null (the Member and Operator are fine).
Any help much appreciated.
Thanks!
--Berry
Make sure you have included kendo.aspnetmvc.min.js. Missing it would lead to similar symptoms.

Kendo Grid filtering with an enumeration

My model contains an enumeration that I'd like to filter the grid on when it's loaded via AJAX.
.cshtml Code:
#(Html.Kendo().Grid()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(x => x.Type);
columns.Bound(x => x.Status); #*This is my enum*#
})
.Filterable()
.DataSource(ds => ds
.Ajax()
.ServerOperation(true)
.Filter(filter => filter.Add(x => x.Status).IsEqualTo(MyEnum.Updated))
.Read(read => read.Action("QueryAlerts", "Alert"))))
The filter request on the AJAX POST is going across as Status~eq~'updated' and returns an Input string was not in a correct format error.
I removed the filtering on the data source and used the filtering controls to see how that request is normally passed which looks like this: Status~eq~2.
I've tried casting the filter values to integers (e.g. filter.Add(x => (int)x.Status).IsEqualTo((int)MyEnum.Updated)) and that results in an invalid cast error to Int32 from the model which is expected by the Add method.
Can this problem be solved using Razor or is this a JavaScript fix?
What data type is your x.Status? If it's an int then you don't need to cast it, only the enumeration:
filter.Add(x => x.Status).IsEqualTo((int)MyEnum.Updated)

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