Using mvc, I have a controller that does a call to a webservice to fetch data and populate a grid every time I refresh the current page.
Is it possible to use ajax to make a call to this service, continuously, resulting in a live feed of data from the service?
This is how my view is setup:
#model FleetMonitorModel
<div class="span12">
<legend>Fleet Monitor</legend>
<div>
#(Html.Kendo().Grid<FleetMonitorModel>()
.Name("Grid")
.DataSource(ds => ds
.Ajax()
.Read(read => read.Action("Get", "FleetMonitor"))
)
.HtmlAttributes(new { style = "height:auto;" })
.Columns(columns =>
{
columns.Template(p => { }).ClientTemplate(" ").Width(310);
columns.Template(p => { }).ClientTemplate(" ").Width(250);
columns.Template(p => { }).ClientTemplate(" ").Width(150);
columns.Template(p => { }).ClientTemplate(" ");
columns.Template(p => { }).ClientTemplate(" ").Width(80);
})
.ClientRowTemplate(Html.Partial("_ClientRowTemplate", Model).ToHtmlString())
.Pageable()
.Sortable())
</div>
</div>
and here is my controller action:
private FleetMonitorModel Model { get; set; }
...
public ActionResult Get([DataSourceRequest] DataSourceRequest request)
{
UnitContract[] listOfUnitsFromService = Client.GetListOfUnits(true);
Model = new FleetMonitorModel()
{
UnitDetails = GenerateUnitDetails(listsOfUnitsFromService.ToList())
};
return Json(Model.UnitDetails.ToDataSourceResult(request));
}
You can call the Grid population method through javascript like this:
var grid = $('#Grid').data('kendoGrid');
grid.dataSource.read();
After that you can call that method repeatedly to update the grid.
Old topic, but I wanted to add the fact that we've successfully implemented SignalR with Kendo components, and it works perfectly :)
Related
I think I'm close. Its not throwing any errors but its also not displaying any data... Im just trying to get it to display a list of Company Names and Company IDs from my TblCompanyInfo table.
This is my controller:
public async Task<IActionResult> Index()
{
var apptReminderContext = _context.TblCompanyInfos.Include(t => t.AcctType).Include(t => t.CompanyStatus).Include(t => t.OnHoldReason);
return View(await apptReminderContext.ToListAsync());
//return View();
}
public JsonResult Products_Read([DataSourceRequest] DataSourceRequest request)
{
DataSourceResult result = _context.TblCompanyInfos.ToDataSourceResult(request,
model => new TblCompanyInfo
{
CompanyId = model.CompanyId,
CompanyName = model.CompanyName
});
return Json(result);
}
and my view...
#model IEnumerable<AppointmentRemindersNetCoreMVC.Models.TblCompanyInfo>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
#using AppointmentRemindersNetCoreMVC.Data
#using Kendo.Mvc.UI
#addTagHelper *, Kendo.Mvc
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#Html.AntiForgeryToken()
#(Html.Kendo().Grid<AppointmentRemindersNetCoreMVC.Models.TblCompanyInfo>()
.Name("grid")
.DataSource(dataSource => dataSource.Ajax()
.Read(read => read.Action("Products_Read", "Company"))
.PageSize(20)
//.ServerOperation(false)
//.Model(model => model.Id(c => c.CompanyId))
//.Read("Products_Read", "Company")
//.Read(read => read.Action("Products_Read", "Company"))
.Update("UpdateCustomer", "Home")
.Create("InsertCustomer", "Home")
.Destroy("DeleteCustomer", "Home"))
.Columns(columns =>
{
columns.Bound(product => product.CompanyName);
columns.Bound(product => product.CompanyId);
})
.Pageable()
.Sortable()
)
Also I know that the Products_Read function is being called by the view and I also know that the "result" contains 32 rows of data. However, nothing is displayed in the grid.
Figured it out! Turns out that json camelcases the return string so the model properties did not match what was returned by json. The solution was to add this line to the Startup.cs file.
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.PropertyNamingPolicy = null);
I'm new to MVC and using kendo ui grid in my project. I've come up with a issue that I'm getting "null" in controller parameter, although data is passing through view. Please see the below code.
Here is my code part from View
#model IEnumerable<WeBOC.Support.Entities.Vessel>
#{
ViewBag.Title = "Vessels";
}
<h2>Vessels</h2>
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(column =>
{
column.Bound(c => c.VIRNbr).Width(100).ClientTemplate(#Html.ActionLink("#=VIRNbr#", "VesselInspector", new { id = "#=VesselVisitId#" }).ToHtmlString()).Title("VIR No.").Width(150);
column.Bound(c => c.VesselName).Width(150).Title("Vessel Name");
column.Bound(c => c.InboundVoyageNbr).Width(70).Title("IB Vyg");
column.Bound(c => c.OutboundVoyageNbr).Width(70).Title("OB Vyg");
column.Bound(c => c.ETA).Width(100).Title("ETA").Format("{0:dd/MM/yyyy HH:mm}");
column.Bound(c => c.ArrivalDate).Width(100).Title("ATA").Format("{0:dd/MM/yyyy HH:mm}");
})
.Groupable()
.Sortable()
.Pageable()
.Filterable()
.DataSource(datasource => datasource
.Ajax()
.ServerOperation(true)
.PageSize(20)
.Read(read => read
.Action("Vessels_Read", "VesselVisit", new { id = "\\#=State\\#"})
))
)
And this is controller method
public ActionResult Vessels_Read([DataSourceRequest] DataSourceRequest request, string id)
{
return Json(GetVessels(id).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
Why I'm getting null in parameter id although passed through view.
public ActionResult Vessels(string id)
{
return View(GetVessels(id));
}
public IEnumerable<Vessel> GetVessels(string phase)
{
IEnumerable<Vessel> vsl = null;
vsl = this._repository.GetVesselByPhase(phase);
return vsl;
}
Any help will be appreciated.
Thanks,
Ovais
If you want to pass additional parameters to your action you should do something like this:
.DataSource( dataSource => dataSource
.Ajax()
.Read( "Vessels_Read", "VesselVisit" ).Data("getState") //getState is a javascript function
)
Then add a script block:
<script>
function getState() {
return {
ID: // your ID, obtained with jQuery, from the View Model, hardcoded, etc...
};
}
</script>
More info here.
EDIT
I have this working right now. I'm working with a View Model but it shouldn't be any different.
View:
.DataSource( dataSource => dataSource
.Ajax()
.Read( "MY_ACTION", "MY_CONTROLLER", new { Id = Model.Id } )
)
Controller:
[HttpPost]
public ActionResult MY_ACTION( [DataSourceRequest] DataSourceRequest request, long Id )
Even if I change new { Id = Model.Id } to new { Id = "QWERTY" } and the action parameter to string, I receive "QUERTY" as the value.
I try to create a Ajax-support Paging Nested Grid in Telerik MVC Extension. I have rendered the Nested Grid in browse, can expand row Genre to show the related Albums filtered by GenreId, but when i use Ajax for this nested Grid, it don't work in grid paging. I have upload my project and post some code about my View and Controller.
When i don't use ajax, the gird can work properly but it cannot expand correctly when browse is reloaded, how can i maintain the state of row which had expanded?
I'm gratiful for any help.
My Project:
http://share.vnn.vn/dl.php/11718146
My View:
#{
ViewBag.Title = "Home Page";
Layout = #"~\Views\Shared\_Layout.cshtml";
}
#( Html.Telerik().Grid<MvcMusicCodeFirsr.Models.Genre>(#Model)
.Name("personGrid")
.DataKeys(keys => keys.Add(k => k.GenreId))
.DataBinding(d => d.Ajax().Update( "_Update", "Home" )
)
// .Editable(editing => editing.Mode(GridEditMode.PopUp))
.Columns(c =>
{
c.Bound(m => m.Name).Width(150);
c.Bound(m => m.Description).Width(150);
//c.Bound(m => m.Birthdate);
c.Command(commands =>
{
commands.Edit();
}).Width(80);
})
.DetailView(detailView =>
detailView.Template(
#<text>
#(Html.Telerik().Grid<MvcMusicCodeFirsr.Models.Album>(item.Albums)
.Name("Albums_" + item.GenreId)
.DataBinding(d => d.Ajax())
.Columns(columns =>
{
columns.Bound(o => o.Title).Width(101);
columns.Bound(o => o.Price).Width(140);
})
.Pageable()
.Sortable()
.Filterable()
)
</text>
)
.ClientTemplate(
Html.Telerik().Grid<MvcMusicCodeFirsr.Models.Album>()
.Name("Albums_<#=GenreId#>")
.DataBinding(d => d.Ajax())
.Footer(false)
.ClientEvents(events => events.OnDataBinding("detailGrid_dataBinding"))
.ToHtmlString()
))
.Sortable()
.Pageable()
)
)
<script type="text/javascript">
function detailGrid_dataBinding(e) {
var grid = $(this).data("tGrid"),
masterRow = $(this).closest("tr.t-detail-row").prev(),
dataItem = $("#Grid").data("tGrid").dataItem(masterRow);
grid.dataBind(dataItem.Albums);
e.preventDefault();
}
</script>
My Controller:
MusicStoreEntities db = new MusicStoreEntities();
public ActionResult Index()
{
return View(db.Genres.ToList());
}
[GridAction]
public ActionResult _Select()
{
return View(new GridModel ( db.Genres.ToList()));
}
[GridAction]
public ActionResult _Update()
{
return View(new GridModel { Data = db.Genres.ToList() });
}
Here is an example showing ajax pading for the nested grid: http://demos.telerik.com/aspnet-mvc/grid/hierarchyajax
I compared the codes with Telerik sample , everything is the same except the model. But I can't see the records in Grid.
// Controller
public ActionResult Index()
{
return View();
}
[GridAction]
public ActionResult _Index()
{
return View(new GridModel<AuctionViewModel>
{
Data = GetData()
}
);
}
// If I replace 'Index' Action codes with '_Index' , the server binding works fine and shows the records but when I try to run AjaxBinding , It doesn't works (never runs _Index codes)
// View
#model List<TestMVC3_Telerik.Models.AuctionViewModel>
#{
Html.Telerik().Grid((List<TestMVC3_Telerik.Models.AuctionViewModel>)ViewData["MyAuctions"])
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.AuctionID).Title("ID").Width(100);
columns.Bound(o => o.AuctionName).Title("Name");
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Index", "Grid"))
.Pageable(paging => paging.PageSize(5))
.Sortable()
.Scrollable()
.Groupable()
.Filterable();
}
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Index", "Grid"))
Change "Grid" to what you are calling the page from
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Index", "Home"))
Once I did that it loaded for me.
I am using free Telerik.Web.Mvc grid and following this example: http://demos.telerik.com/aspnet-mvc/grid/hierarchyajax
My Issue:
I am populating the grid with search results after user input some data and submit with a search button
In the DetailView() method I reference my 'SearchQuote_QuotesForHierarchyAjax' method, which is in defined in my Controller when DetailView executes data should be fetched, but this controller action does not execute for me.
If i load the grid first time page loads it execute. but not when the grid is loaded in a search button click
The Code in my project:
My SearchQuote.aspx View looks like this
<%= Html.Telerik().Grid(Model.QuoteSummaryList)
.Name("SearchQuoteGrid")
.Columns(columns =>
{
columns.Bound(q => q.QuoteId).Title("Quote #").Width(50);
columns.Bound(q => q.AxiomId).Title("Axiom Id").Width(180);
})
.ClientEvents(events => events.OnRowDataBound("quotes_onRowDataBound"))
.DetailView(details => details.ClientTemplate(
Html.Telerik().Grid(Model.QuoteSubSummaryList)
.Name("Quotes_<#= QuoteId #>")
.Columns(columns =>
{
columns.Bound(o => o.PositionCode).Width(101);
columns.Bound(o => o.Group).Width(140);
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("SearchQuote_QuotesForHierarchyAjax", "SearchQuote", new
{quoteid ="<#= QuoteId #>"}))
.Pageable()
.Sortable()
.Filterable()
.ToHtmlString()
))
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("SearchQuote_Select", "SearchQuote"))
.Sortable()
.Pageable(p => p.PageSize(3))
%>
<script type="text/javascript">
function expandFirstRow(grid, row) {
if (grid.$rows().index(row) == 0) {
grid.expandRow(row);
}
}
function quotes_onRowDataBound(e) {
var grid = $(this).data('tGrid');
expandFirstRow(grid, e.row);
}
</script>
And SearchQuoteController has this code.
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult SearchQuote_QuotesForHierarchyAjax(int quoteid)
{
List<QuoteLineSummaryDM> sublist = new List<QuoteLineSummaryDM>();
QuoteLineSummaryDM a = new QuoteLineSummaryDM();
a.PositionCode = "50";
a.Group = "1";
sublist.Add(a);
QuoteLineSummaryDM b = new QuoteLineSummaryDM();
b.PositionCode = "40";
b.Group = "2";
sublist.Add(b);
var qrows = (from r in sublist
select r).AsQueryable();
return View(new GridModel(qrows));
}
What am I missing? My version is even simpler than the demo. Any ideas?
Thanks.
I found another grid that does what I want to do. It's called jqGrid