Reputation: 47
I have a controller that returns a strongly typed view and the results of a dynamic sql procedure datatable via Viewbag. I'm trying to bind the grid to the Viewbag data in my view but I cant figure out how to do so.
@(Html.Kendo().Grid(ViewBag.Rev)
.Name("RevGrid")
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
))
public ActionResult Index()
{
using (DataContext db = new DataContext())
{
var spring = db.SpringTrainings.ToList();
ViewData["Rev"] = Revenue();
return View(spring);
}
}
This is where the datatable comes from:
public DataTable Revenue()
{
using (var conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
using (var commandproc = conn.CreateCommand())
{
commandproc.CommandType = System.Data.CommandType.StoredProcedure;
commandproc.CommandText = "stTicketRevenue";
conn.Open();
{
var dataTable = new DataTable();
var dataReader = commandproc.ExecuteReader();
dataTable.Load(dataReader);
ViewBag.Proc = dataTable;
conn.Close();
return dataTable;
}
}
}
}
I would really appreciate some help with this. I'm not even sure this is the right way to pass the datatable from the controller.
Upvotes: 0
Views: 6873
Reputation: 26
@(Html.Kendo().Grid(ViewBag.Rev as System.Data.DataTable)
.Name("RevGrid")
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
))
(OR)
@(Html.Kendo().Grid(ViewData["Rev"] as System.Data.DataTable)
.Name("RevGrid")
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
))
It will give error if you not cast the ViewBag or ViewData to either DataTable or List. Err -> Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
Rather using ViewBag or ViewData, use Kendo read action to get the data from db. So that the page will load very fast and once after page got loaded to user, kendo grid will do ajax call for binding data into it.
@(Html.Kendo().Grid(new List<UI.Models.TestViewModel>())
.Name("RevGrid")
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetDataTableAction", "ControllerName"))
.PageSize(20)
.ServerOperation(false)
))
And controller method looks like
public ActionResult GetDataTableAction([DataSourceRequest] DataSourceRequest request)
{
List<Model> model = new List<Model>();
DataSourceResult result = model.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
Upvotes: 1