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.
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 want to show users in a Kendo Grid. Here is my Controller:
public class UserController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Users_Read([DataSourceRequest]DataSourceRequest request)
{
using (var rahatWeb = new RahatWebEntities())
{
IQueryable<User> users = rahatWeb.Users;
DataSourceResult result = users.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
Here is my View:
#{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#(Html.Kendo().Grid<RahatWeb.Models.User>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(user => user.Id);
columns.Bound(user => user.FirstName);
columns.Bound(user => user.LastName);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Users_Read", "User"))
)
.Pageable()
.Sortable()
)
The problem is that no data is shown in Grid. How can I solve the issue?
Have you included kendo.aspnetmvc.min.js in your layout? Also, hit F12 in your browser and check the console for any client-side errors.
I am having an issue where the READ operation for the Kendo Grid does not get invoked and hence the grid does not populate any data. I have followed these links
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/troubleshooting#the-ajax-bound-grid-does-not-populate
Kendo UI Grid is not calling READ method
However the issue still exists.
/// CS File
public ActionResult GetItemsHome([DataSourceRequest] DataSourceRequest request , int page)
{
List<CustomItem> lst = new List<CustomItem>();
return Json(lst.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
///cs html file
#(Html.Kendo().Grid<CustomItem>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.No).Width("15%");
columns.Bound(o => o.ShortDesc).Width("15%");
columns.Bound(o => o.Category).Width("6%");
})
.Sortable()
.Pageable(p=>p.Refresh(true))
.Filterable()
.Scrollable()
.Editable(edit => edit.DisplayDeleteConfirmation("Are You Sure To Delete This ").Mode(GridEditMode.PopUp))
.ColumnMenu(col=>col.Sortable(false))
.Groupable()
.ToolBar(toolbar => toolbar.Create())
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
//.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(6)
.Read(read => read.Action("GetItemsHome", "det"))
.Model(model => {
model.Id(p => p.ID);
})
.Create(update => update.Action("EditingInline_Create", "det"))
// .Read(read => read.Action("EditingInline_Read", "Default1"))
.Update(update => update.Action("EditingInline_Update", "det"))
.Destroy(update => update.Action("EditingInline_Destroy", "det"))
)
)
the order in which the JS is loaded
Any ideas ?
Thanks
Your action GetItemsHome([DataSourceRequest] DataSourceRequest request , int page) requires page (non-null value) to be passed. You have 3 options:
Delete this argument (this makes sense since request contains everything you want)
Supply it like: .Read(read => read.Action("GetItemsHome", "det", new { page = 10}))
Make it nullable like: int? page
EDIT: After following any of above, return some data from controller action (I am creating some arbitrary data, you may return it from DB instead) to fill up your grid. Something like:
public ActionResult GetItemsHome([DataSourceRequest] DataSourceRequest request , int? page)
{
//List<CustomItem> lst = new List<CustomItem>();
// Dummy data
var data = new [] { new CustomItem(){ No = 1, ShortDesc = "xyz", Category = "abc"},
new CustomItem(){ No = 2, ShortDesc = "xyz", Category = "abc"} };
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
If your controller and action names are spelled correctly in view, above code should work.
Some possibilities, if your function is not being called:
If your ActionResult Index() function is doing some other operations instead of simply return View() and exiting, it's possible your GetItemsHome() function may not be called - I had this issue once.
Try just naming the function "Read" instead of "GetItemsHome".
Does your controller have any other functions (i.e. Update, Destroy)? I would comment them out, in case there are syntax issues in them that are causing the issue.
"det", I hope, is the name of your controller.
Why pass in the extra page parameter at all? Try it without it, and use a public variable in your model to hold that value.
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 :)
The json result is just being displayed on the screen and not populating the grid.
public ActionResult BulkEdit([DataSourceRequest]DataSourceRequest request)
{
var NewAssets = db.TurnaroundDumps;
DataSourceResult result = NewAssets.ToDataSourceResult(request)
return Json(result, JsonRequestBehavior.AllowGet);
}
Then on my view:
#(Html.Kendo().Grid<PcInventory_v1_1.Models.TurnaroundDump>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.AssetTag);
columns.Bound(p => p.SerialNumber);
columns.Bound(p => p.DeptId);
columns.Bound(p => p.Location);
})
.DataSource(dataSource => dataSource
.Ajax() // Specify that the data source is of ajax type
.Read(read => read.Action("BulkEdit", "Assets"))
// Specify the action method and controller name
).Pageable()
)
What is going wrong?
I had forgot to return the view.
Here is the answer:
public ActionResult BulkEdit()
{
return View();
}
[HttpPost]
public ActionResult BulkEdit([DataSourceRequest]DataSourceRequest request)
{
var emp = db.TurnaroundDumps;
DataSourceResult result = emp.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}