I am trying to get a telerik grid to display json data that is being return from a controller action but the only it displays the actual json data in the browser window.
Am i supposed to call .BindTo after read?
Am i doing something wrong in my action?
am i going about this all wrong?
[HttpGet]
public ActionResult ReadLeads([DataSourceRequest]DataSourceRequest request)
{
var model = new RecordLookupViewModel();
using (var db = new RGI_MasterEntities())
{
db.Configuration.ProxyCreationEnabled = false;
var results = db.tblMasterLeads
.Where(
x => (model.FirstName == null || x.FirstName.Equals("Eric"))
&& (model.RecordType == null || x.MasterLeadType.Equals("Responder"))
)
.Select(s => new LookupGridResults
{
FirstName = s.FirstName,
LastName = s.LastName,
City = s.city,
State = s.state,
County = s.county,
Zip = s.zip
}).Take(10);
var result = results.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
Hers is my view code for the grid.
#(Html.Kendo().Grid<LookupGridResults>()
.Name("grid")
.AutoBind(false)
.Columns(columns =>
{
columns.Bound(p => p.FirstName).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains"))).Width(225);
columns.Bound(p => p.LastName).Width(225).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
columns.Bound(p => p.City).Width(225).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
columns.Bound(p => p.County).Width(225).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
columns.Bound(p => p.State).Width(225).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
columns.Bound(p => p.Zip).Width(225).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(true)
.Read(read => read.Action("ReadLeads", "LeadsManagement").Type(HttpVerbs.Get))
)
)
Here are my results btw.
{"Data":[{"LastName":"COFFEY","FirstName":"EDWARD","City":"FRANKFORT","County":"FRANKLIN","State":"KY","Zip":"40601-2304"},{"LastName":"DESPAIN","FirstName":"TONY","City":"CAMPBELLSVILLE","County":"TAYLOR","State":"KY","Zip":"42718-9397"},{"LastName":"HALBIG","FirstName":"RONALD","City":"CAMPBELLSVILLE","County":"TAYLOR","State":"KY","Zip":"42718-1556"},{"LastName":"KRAUS","FirstName":"REBECCA","City":"FRANKFORT","County":"FRANKLIN","State":"KY","Zip":"40601-2714"},{"LastName":"LAWLESS","FirstName":"MEREDITH","City":"CAMPBELLSVILLE","County":"TAYLOR","State":"KY","Zip":"42718-1556"},{"LastName":"RANKIN","FirstName":"PAULINE","City":"LAWRENCEBURG","County":"ANDERSON","State":"KY","Zip":"40342-1374"},{"LastName":"SHIRLEY","FirstName":"LORRAINE","City":"CAMPBELLSVLLE","County":"TAYLOR","State":"KY","Zip":"42718-1557"},{"LastName":"STAPLES","FirstName":"DAMON","City":"HODGENVILLE","County":"LARUE","State":"KY","Zip":"42748-1208"},{"LastName":"WILLIAMS","FirstName":"LUCY","City":"FRANKFORT","County":"FRANKLIN","State":"KY","Zip":"40601-2308"},{"LastName":"WILSON","FirstName":"BELIDA","City":"FRANKFORT","County":"FRANKLIN","State":"KY","Zip":"40601-1321"}],"Total":10,"AggregateResults":null,"Errors":null}
Thanks for all the help, it seemed i was missing a reference to a bundle. I do credit Mark Schultheiss for pointing me in the right direction.
Got it completly working today. Here is what fixed it.
I changed my actionresult to a JsonResult.
I had filtering turned on in the grid but none of my columns had filtering attributes.
I think thats about it. It works great now.
Related
I'm using asp.net core razor pages with a Kendo Grid that is datasourced using SignalR. It gets the initial read ok, but the update does not fire. I've looked at the Kendo Demo, and other stackover flow pages, but nothing seems to work.
I know the API works fine in sending the update because I see the call when debugging through Chrome that the websocket received an update commmand with the new data in json format. But the Grid doesn't update, or fire any update commands. It's as if it never received it, or doesn't know that it received it.
Index.cshmtl
<script src="~/signalr/signalr.js"></script>
<script>
var url = https://demosite.com/hub/controller;
var hub = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Information)
.withUrl(url,
{
transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling
})
.build();
var hubStart = hub.start();
</script>
#(Html.Kendo().Grid<myModel>
()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Bound(c => c.Date);
})
.HtmlAttributes(new { style = "width: 98%;" })
.DataSource(dataSource => dataSource
.SignalR()
.AutoSync(true)
.ServerFiltering(true)
.ServerSorting(true)
.PageSize(10)
.Transport(tr => tr
.Promise("hubStart")
.Hub("hub")
.Client(c => c
.Read("read") //Read works, initial data loads
.Create("create")
.Update("update")
.Destroy("destroy")
)
.Server(s => s
.Read("read")
.Create("create")
.Update("update")
.Destroy("destroy")
)
)
.Schema(schema => schema
.Data("Data")
.Total("Total")
.Aggregates("Aggregates")
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p=> p.Name);
model.Field(p => p.Date);
}
)
)
)
.Group(g => g.Add(x => x.Name))
)
.Events(x=>
{
x.DataBound("collapseAllGroups");
}
)
.Groupable(true)
.Sortable()
.Filterable()
.Pageable(pager => pager.AlwaysVisible(true).PageSizes(new int[] { 10, 20, 50, 100 }))
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Selectable()
)
Api
[HttpGet]
public async Task<myModel> GetTest()
{
myModel mod= new myModel();
mod.Name = "New Name";
mod.Date = DateTime.UTCNow.ToString();
//Send update command to connected SignalR Clients
await _hub.Clients.All.SendAsync("update", mod);
return mod;
}
Any help would be appreciated.
Ok I got this to work. Turns out that since the Grid is originally expecting a DataSourceResult I had to convert myModel to a DataSourceResult type before doing the update. Example below should be considered Pseudocode as I’m typing this on my phone.
await _hub.Clients.All.SendAsync("update", new DataSourceResult(mod));
Telerik Kendo MVC Grid - How do I set onload/initial filter equals True with checkbox columns?
I am trying to set a True/False column filter to True on initial load. My Viewmodel has a bool property called IsHoliday. I have followed the example in the link above but i don't have any records showing in the grid at startup. My read action returns a JSON of IEnumerable as suggested in the referenced link. My View is as follows:
#(Html.Kendo().Grid<HolidayVM>()
.Name("h_grid")
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
.ServerOperation(false)
.Events(events => events.Error("grid_error")) // Handle the "error" event
.Model(model =>
{
model.Id(m => m.Date);
model.Field(m => m.Date).Editable(false);
})
.Filter(f => f.Add(m => m.IsHoliday.Equals(true)))
.Read(read => read.Action("Holiday_Read", "Holiday"))
.Update(up => up.Action("Holiday_Update", "Holiday").Data("grid_sendAntiForgery"))
)
.Columns(columns =>
{
columns.Bound(p => p.Date).Width(30).Format("{0:dd-MMMM}");
columns.Bound(p => p.HolidayText).Width(100).Filterable(false);
columns.Bound(p => p.IsHoliday)
.ClientTemplate("<input type='checkbox' #= IsHoliday ? '' : checked='checked' # disabled='disabled' />")
.Filterable(ftb => ftb.Cell(cell => cell.Operator("Is equal to")))
.Width(30);
columns.Command(cmd =>
{
cmd.Edit().HtmlAttributes(new { title = "Edit" });
}).Title("Commands").Width(25);
})
.Pageable()
.Sortable()
)
Ideally I will like my grid to look like in attached image, on load, with IsHoliday set to True
I finally figured it out.
.Filter(f => f.Add(m => m.IsHoliday).IsEqualTo(true))
instead of
.Filter(f => f.Add(m => m.IsHoliday.Equals(true)))
use this easily:
columns.Bound(p => p.ISProperty).ClientTemplate("#= ISProperty? 'Yes' : 'No' #")
The error that i have received when tried to sort the Kendo grid by clicking on the Customer ID column is: {"Invalid property or field - 'CustomerID' for type: OMS_CUSTOMER"}. What else is needed to bind the columns of grid, model view and model. Thanks
controller _read function:
IQueryable<OMS_CUSTOMER> CustomerList = this.dbContext.OMS_CUSTOMERs;
DataSourceResult result = CustomerList.ToDataSourceResult(request
, ModelState
, c => new CustomerViewModel
{
CustomerID = c.OMS_CUSTOMER_ID,
CustomerName = c.CUSTOMERNAME
});
return Json(result);
View:
#model IEnumerable<NCBA.ViewModels.CustomerViewModel>
#(Html.Kendo().Grid<NCBA.ViewModels.CustomerViewModel>()
.Name("grid-CustomerViewModel")
.DataSource(dataSource => dataSource
.Ajax()
.Model(
model =>
{
model.Id(cust => cust.CustomerID);
}
)
.Create(create => create.Action("_Create", "Customer"))
.Read(read => read.Action("_Read", "Customer"))
.Update(update => update.Action("_Update", "Customer"))
.Destroy(destroy => destroy.Action("_Delete", "Customer"))
)
.Columns(columns =>
{
columns.Bound(c => c.CustomerID);
columns.Bound(c => c.CustomerName);
columns.Command(commands =>
{
commands.Edit();
commands.Destroy();
}).Title("Commands").Width(200);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Pageable()
.Sortable()
)
I have a Kendo Grid (MVC Razor) that I am trying to have pass extra data to the controller via the .Data call off of the Read method:
#(Html.Kendo().Grid<AssignedSiteGridPoco>()
.Name("UnAssignedSiteGrid")
.Filterable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Columns(columns =>
{
columns.Bound(p => p.SiteId).Hidden();
columns.Bound(p => p.SiteName).Title("Site Name").Width(180);
columns.Bound(p => p.City).Title("City").Width(80);
columns.Bound(p => p.StateName).Title("State Name").Width(100);
columns.Command(command => command
.Custom("Add")
.Click("unassignedSiteGridClick")
).Width(90);
})
.Scrollable()
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Resizable(resize => resize.Columns(true))
.Events(events =>
{
//events.Change("GridChange");
//events.DataBound("OnDataBound");
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.SiteId);
model.Field(p => p.SiteName);
model.Field(p => p.City).Editable(false);
model.Field(p => p.StateName).Editable(false);
})
.PageSize(15)
.Read(read => read.Action("GetUnassignedSiteGridDataList", "Manager").Data("getUserRightName"))
))
The Javascript block, placed above the grid div, is as follows:
function getUserRightName() {
return
{
UserRightName : "2"
};
}
And the controller:
public JsonResult GetUnassignedSiteGridDataList([DataSourceRequest]DataSourceRequest request, string UserRightName)
{
var model = new AssignedSiteGridPoco();
var siteList = _managerPresentationService.GetUnassignedSiteGridDataList(model);
return Json(siteList.ToDataSourceResult(request));
}
The string value being passed from the view's read method is null in the "UserRightName" string. According to the examples, it should pass back the text value "2" My Version of Kendo is: 2014.2.807 InternalBuild. Is there a problem in this build in this area?
Thanks,
Steven
Wrap the key name in the json structure into quotes i.e.
change your js function to this:
function getUserRightName() {
return {'UserRightName':"2"};
}
How do i restrict the kendo datetime picker to allow only to select date ?
Currently a clock icon appears next to the Date picker, i don't want that.
The fields which ends with date are my date columns.
All the date fields are nullable date column (i.e DateTime?)
Can anyone point me right direction?
Here is my razor :
#(Html.Kendo().Grid(Model.employeedetailsList)
.Name("DependentGrid")
.Columns(columns =>
{
columns.ForeignKey(p => p.TitleCode, Model.TitleList, "TitleCode", "TitleDescription").Title("Title").Width(130);
columns.Bound(p => p.FirstName).Title("First Name");
columns.Bound(p => p.MiddleName).Title("Middle Name");
columns.Bound(p => p.LastName).Title("Last Name"); ;
columns.ForeignKey(p => p.Gender, Model.GenderList, "TitleCode", "TitleDescription").Title("Gender");
columns.ForeignKey(p => p.RelCode, Model.RelList, "RelCode", "RelName").Title("Rel");
columns.Bound(p => p.DepDOB).Format("{0:dd-MMM-yyyy}").Title("Date of Birth");
columns.Bound(p => p.RelStartDate).Format("{0:dd-MMM-yyyy}").Title("Rel Start Date");
columns.Bound(p => p.RelEndDate).Format("{0:dd-MMM-yyyy}").Title("Rel End Date");
columns.Bound(p => p.EmailAddress).Title("Email");
columns.Bound(p => p.DepPassportNumber).Title("Passport Number");
columns.Bound(p => p.DepPassportExpDate).Format("{0:dd-MMM-yyyy}").Title("Passport Expiry Date");
columns.Bound(p => p.RPNumber);
columns.Bound(p => p.RPIssueDate).Format("{0:dd-MMM-yyyy}").Title("RP Issue Date");
columns.Bound(p => p.RPExpDate).Format("{0:dd-MMM-yyyy}").Title("RP Expiry Dates");
})
.Sortable()
.Resizable(resize => resize.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(m => m.DependantDetialId);
})
.Update(update => update.Action("employeedetails_Update", "Mycontroller")
.Data("additionalData"))
.Create(create => create.Action("employeedetails_Create", "Mycontroller")
.Data("additionalData"))
.Destroy(delete => delete.Action("employeedetails_Destroy", "Mycontroller")
)
.Events(e => e.RequestEnd("DependentGrid_onComplete")
)
)
)
This was far easier, for me. If you're using MVC, in your model, you just tell it to use DataType.Date:
[DataType(DataType.Date)]
public DateTime RelStartDate{ get; set; }
You will need using System.ComponentModel.DataAnnotations; at the top of your page to include these tags.
Source: http://www.telerik.com/forums/remove-time-timepicker-from-grid
What I usually do when I only want the date and not the time is to create an Editor Template for that specific field.
Inside your view folder you create a new folder named EditorTemplates. In your case that might be /Views/Employees/EditorTemplates. Inside that folder you create a file named RelStartDate.cshtml which we'll use to display the DatePicker control.
In the new file you add the following lines:
#model DateTime?
#(Html.Kendo().DatePicker()
.Name("RelStartDate")
.Value(Model == null ? DateTime.Now.Date : ((DateTime)#Model).Date)
)
To use it you just have to write
columns.Bound(p => p.RelStartDate).EditorTemplateName("EmployeeDate");
A la propiedad del modelo tienes que poner una anotación ejemplo:
[UIHint("Date")]// o [DataType(DataType.Date)]
[Display(Name = "Fecha2")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = " {0:MM/dd/yyyy}")]
public DateTime? fecHastaCuentaExenta { get; set; }