net mvc4 project with Kendo UI iam using a simple ajax grid to print values from the database but it is not showing on the grid my code is
<%: Html.Kendo().Grid<CustomerTest.Models.ProductViewModel>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read
.Action("Printc", "Home") // Set the action method which will return the data in JSON format
// .Data("productsReadData") // Specify the JavaScript function which will return the data
)
)
.Columns(columns =>
{
columns.Bound(product => product.CustomerID);
columns.Bound(product => product.CustomerFName);
columns.Bound(product => product.CustomerLName);
})
.Pageable()
.Sortable()
%>
and my action method is
public ActionResult Printc()
{
// ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(GetCustomers());
}
private static IEnumerable<ProductViewModel> GetCustomers()
{
var northwind = new CustomerLinqDataContext();
var purchCount = northwind.Customer_details.Count();
return northwind.Customer_details.Select(product => new ProductViewModel
{
CustomerID = product.ID,
CustomerFName = product.name,
CustomerLName = product.lname,
CustomerAge = product.age
});
}
please some one help me put what i am doing wrong? i tried to pass my model on the page header
<%# Page Title="" Language="C#" MasterPageFile="~/Areas/aspx/Views/Shared/Web.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<CustomerTest.Models.ProductViewModel>>" %>
It worked fine but i have mutiple grids on my single page and they are coming from different tables so thats why i want to pass each model differently please someone help me in this code thanks
The problem is on your Printc method. You have to return a Json object create for the Kendo Grid :
public ActionResult Index_Printc([DataSourceRequest] DataSourceRequest request)
{
return Json(GetCustomers().ToDataSourceResult(request));
}
On my side, I specify the ID on the Ajax request, I don't know if it's mandatory for a read request, but if the update of the method doesn't work, add this :
<%: Html.Kendo().Grid<CustomerTest.Models.ProductViewModel>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.CustomerID))
.Read(read => read.Action("Printc", "Home")
)
)
.Columns(columns =>
{
columns.Bound(product => product.CustomerID);
columns.Bound(product => product.CustomerFName);
columns.Bound(product => product.CustomerLName);
})
.Pageable()
.Sortable()
%>
Hope it helps !
if you have several grids on the same page make sure that they have unique names and not all of them are called grid.
Related
I'm new to Kendo and learning how to integrate it with MVC and display data in a grid.
My controller
[HttpGet]
public ActionResult StudentList([DataSourceRequest]DataSourceRequest request)
{
DataSourceResult result =
_acc.GetStudent(StudId).ToDataSourceResult(request,
model => new StudentModel
{
ID = model.ID,
StudId = model.StudId,
Name= model.Name,
Email= model.FullName,
custEmail = model.Email
});
return Json(result, JsonRequestBehavior.AllowGet);
}
My view
#(Html.Kendo().Grid<Models.StudentModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.StudId);
columns.Bound(c => c.Name);
columns.Bound(c => c.Email);
})
.Pageable()
.Sortable()
.Filterable()
.Scrollable(scr => scr.Height(550))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("StudList", "Student"))
.ServerOperation(false)
)
)
And the out put I am getting in my browser looks like
{"Data":[{"ID":1102,"StudId":4006,"Name":"Adam Lyon","Email":"alyon#regionofwaterloo.ca",",....,
Does anyone has any idea why the data is not formatted in a grid form?
You will get that behavior if you link directly to the EmployeeList action - that should only be called by the grid. If your view name is say Index, you will need another action:
public ActionResult Index()
{
return View();
}
Then in code link to that:
#Html.ActionLink("Employee List", "Index", "Employee")
Now the view will load and the Kendo grid will render and then call your EmployeeList action to populate the grid.
See the Kendo sample controller here. It has an action to load the view with the grid, and then CRUD actions the grid will call via AJAX.
When I set the datasource to WebAPI binding, the HTTP GET is being invoked on the controller and it returns the correct data. The problem is that my Kendo Grid is not binding the data correctly, instead I get an empty grid as a result.
#(Html.Kendo().Grid(Model)
.Name("Accounts")
.Columns(columns =>
{
columns.Bound(c => c.Description).Title("Account Name");
columns.ForeignKey(c => c.Type, (System.Collections.IEnumerable)ViewData["accountTypes"], "Id", "Name").Title("Account Type");
columns.ForeignKey(c => c.Currency, (System.Collections.IEnumerable)ViewData["currencyTypes"], "Id", "Name").Title("Account Currency");
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(210);
})
.Sortable(sortable =>
{
sortable.SortMode(GridSortMode.SingleColumn);
sortable.AllowUnsort(false);
})
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.ToolBar(toolbar => { toolbar.Create(); })
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.WebApi()
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Currency).DefaultValue(0).Editable(true);
model.Field(p => p.Description).Editable(true);
model.Field(p => p.Type).Editable(true);
})
.ServerOperation(true)
.Read(read => read.Action("Get", "Accounts"))
.Create(create => create.Action("Post", "Accounts"))
.Update(update => update.Action("Put", "Accounts", new { id = "{0}" }))
.Destroy(destroy => destroy.Action("Delete", "Accounts", new { id = "{0}" }))
.PageSize(10)
)
)
Controller
// GET: api/values
[HttpGet]
public DataSourceResult Get([DataSourceRequest]DataSourceRequest request)
{
return _context.Accounts.ToDataSourceResult(request);
}
I always get an HTTP 200 OK as a result of the paging or sorting command, but the grid is empty afterwards. The URL generated by Kendo is:
http://localhost:58829/Accounts/Get?sort=&page=1&pageSize=10&group=&filter=
Which actually returns JSON when I open it with a browser.
The problem seems to be that you are mixing two different ways to load the data. On the one hand you are passing the Model by param to the grid (this approach is used when ServerOperation = false) and on the other hand you are setting ServerOperation = true and specifying a read action.
The reason why the grid is empty in this case is probably because either the Model is empty.
Take a look at this demo example for a reference on how to implement the remote source databinding: http://demos.telerik.com/aspnet-core/grid/remote-data-binding
Example View:
Example controller:
Hope this helps KendoGrid is an awesome library but like many other libraries it could definitely use better exception handling and more user friendly exceptions :) In my opinion the grid should have shown an exception in this case.
The problem was this: when declaring the Kendo Grid and passing the Model as a parameter like so:
#(Html.Kendo().Grid(Model)
You need to remove the .Read() action, and make sure to use .ServerOperation(false). This works either with WebApi binding or Ajax binding:
.DataSource(dataSource => dataSource
.WebApi() // also works with .Ajax()
.Model(model =>
{
model.Id(p => p.Id);
}
)
.ServerOperation(false)
.Create(create => create.Action("Post", "Invoices"))
.Update(update => update.Action("Put", "Invoices", new { id = "{0}" }))
.Destroy(destroy => destroy.Action("Delete", "Invoices", new { id = "{0}" }))
.PageSize(10)
)
Also, the DataSourceResult Get() method can be removed.
Im trying to use incell editing and use of the http://demos.telerik.com/aspnet-mvc/grid/editing-custom but is can't find my partial view that the dropdownlist should be rendered from.
Partial view (Testview.cshtml)
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownList()
.Name("ResourceType") // Name of the widget should be the same as the name of the property
.DataValueField("Id") // The value of the dropdown is taken from the EmployeeID property
.DataTextField("Name") // The text of the items is taken from the EmployeeName property
.BindTo((System.Collections.IEnumerable)ViewData["defaultResourceType"]) // A list of all employees which is populated in the controller
)
This is my grid:
#(Html.Kendo().Grid<RMS.Admin.ViewModel>()
.Name("ResourceGrid")
.Columns(columns =>
{
columns.Bound(c => c.ResourceId).Hidden();
columns.Bound(c => c.ResourceName);
columns.Bound(c => c.Descritption);
columns.Bound(c => c.ResourceType.Name).ClientTemplate("#=ResourceType.Name#");
columns.Bound(c => c.Approved);
columns.Bound(c => c.IsEnabled);
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(172).Title("Edit/Delete");
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(s => s.ResourceId);
model.Field(s => s.ResourceType).DefaultValue(ViewData["defaultResourceType"] as RMS.Admin.ViewModel.ResourceTypeId);
})
.Create(update => update.Action("CreateResource", "Home"))
.Read(read => read.Action("ReadResource", "Home"))
.Update(update => update.Action("SaveSystem", "Home"))
.Destroy(destroy => destroy.Action("RemoveSystem", "Home"))
)
)
Here is a part of my model:
public string ResourceUserId { get; set; }
[UIHint("Testview")]
public ResourceTypeId ResourceType { get; set; }
This is in my controller where i bind the data:
private void GetResourceTypeId()
{
//string [] list = new string[]{"Image", "Document", "Other"};
IList<ViewModel.ResourceTypeId> list = new List<ViewModel.ResourceTypeId>();
var a = new ViewModel.ResourceTypeId
{
Name = "Image",
Id = 1
};
var b = new ViewModel.ResourceTypeId
{
Name = "Document",
Id = 2
};
var c = new ViewModel.ResourceTypeId
{
Name = "Other",
Id = 3
};
list.Add(a);
list.Add(b);
list.Add(c);
ViewData["defaultResourceType"] = list.First();
}
I get this error when trying to render the grid:
The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
What am i missing?
First off your trying to bind just to one item with ViewData["defaultResourceType"] = list.First();. Instead you should bind to your whole list and then set the default option with .Value("1") so that it has "Images" by default.
#(Html.Kendo().DropDownList()
.Name("ResourceType")
.DataValueField("Id")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["ResourceTypeList"])
.Value(ViewData["DefaultResourceType"])
);
Also for a template for a column in MVC you may just want to set it with EditorTemplateName
columns.Bound(e => e.myColumn).EditorTemplateName("dropdownTemplate")
And then define the template that you want to use somewhere else on the page.
<script id="dropdownTemplate" type="text/x-kendo-template">
#(Html.Kendo().DropDownList()
.Name("myDropDown")
.....
.ToClientTemplate()
)
</script>
If you would like you can also declare it as a stand alone template in your /Views/Shared/ folder. You would not have to add the .ToClientTemplate() or the script tags. You would reference it by the file name. You could then use the template on multiple pages in the project.
I am using the following code. Can anybody tell me how will I use the page number instead of scroll bar?
My Index.cshtml page will be like
<div id="CustomerProfile">
<div id="GridCusotmerProfile">
#(Html.Kendo().Grid(Model)
.Name("grdCustomerProfile")
.Columns(coloumns =>
{
coloumns.Bound(p => p.CustomerID).Title("Customer ID");
coloumns.Bound(p => p.UserId).Title("User Id");
coloumns.Bound(p => p.ComapnyName).Title("Company Name");
coloumns.Bound(p => p.ContactPerson).Title("Contact Person");
coloumns.Bound(p => p.AccountNumber).Title("Account Number");
}
)
.Sortable()
.Scrollable(scrollable => scrollable.Virtual(true))
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read.Action("Virtualization_Read", "CustomerProfile"))
)
)
</div>
My Controller will be like the following
public List<CustomerProfileModel> CustomerDataSource(int page, int pagesize, int skip, int take)
{
List<CustomerProfileModel> ModelData = new List<CustomerProfileModel>();
take = skip + take + (page * 10);
var CustomerData = (from cp in context.CustomerProfile select cp).OrderBy(x => x.ComapnyName).Take(take).Skip(skip).ToList();
foreach (var items in CustomerData)
{
CustomerProfileModel Model = new CustomerProfileModel();
Model.CustomerID = items.CustomerID;
Model.AccountNumber = items.AccountNumber;
Model.ComapnyName = items.ComapnyName;
Model.ContactPerson = items.ContactPerson;
Model.UserId = items.UserId;
ModelData.Add(Model);
}
return ModelData;
}
public ActionResult Virtualization_Read([DataSourceRequest] DataSourceRequest request, string page,string pagesize,string skip,string take)
{
return Json(CustomerDataSource(Convert.ToInt32(page),Convert.ToInt32(pagesize),Convert.ToInt32(skip),Convert.ToInt32(take)).ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
public List<CustomerProfileModel> CustomerDataSource(int page, int pagesize, int skip, int take)
{
List<CustomerProfileModel> ModelData = new List<CustomerProfileModel>();
take = skip + take + (page * 10);
var CustomerData = (from cp in context.CustomerProfile select cp).OrderBy(x => x.ComapnyName).Take(take).Skip(skip).ToList();
foreach (var items in CustomerData)
{
CustomerProfileModel Model = new CustomerProfileModel();
Model.CustomerID = items.CustomerID;
Model.AccountNumber = items.AccountNumber;
Model.ComapnyName = items.ComapnyName;
Model.ContactPerson = items.ContactPerson;
Model.UserId = items.UserId;
ModelData.Add(Model);
}
return ModelData;
}
public ActionResult Virtualization_Read([DataSourceRequest] DataSourceRequest request, string page,string pagesize,string skip,string take)
{
return Json(CustomerDataSource(Convert.ToInt32(page),Convert.ToInt32(pagesize),Convert.ToInt32(skip),Convert.ToInt32(take)).ToDataSourceResult(request),JsonRequestBehavior.AllowGet);
}
Please let me know if I need something else to get data as lazy loading.
Your on the right tracks, but it is actually a lot easier than you think. Your trying to hand roll functionality that Kendo handles with the `ToDataSourceResult() extension method.
The DataSourceRequest contains all the information needed for database operations, such as ordering, aggregates and paging. So you can simplfy your code down to pretty much the following (NOT TESTED)
public ActionResult Virtualization_Read([DataSourceRequest] DataSourceRequest request)
{
var CustomerData = (from cp in context.CustomerProfile select cp); // don't call toList() this exectues the SQL and pulls data into memory, leave it as a Queryable object so we can pass it to kendo to add its expressions this will the be a Database operation
DataSourceResult result = CustomerData.ToDataSourceResult(request, x => new CustomerProfileModel(){
CustomerID = x.CustomerID;
AccountNumber = x.AccountNumber;
ComapnyName = x.ComapnyName;
ContactPerson = x.ContactPerson;
UserId = x.UserId;
});
return Json(result);
}
For further reading take a look at this link:
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
From the Kendo Site:
How do I implement paging, sorting, filtering and grouping?
If your model supports the IQueryable interface or is DataTable the grid will do paging, sorting, filtering, grouping and aggregates automatically. For server binding scenarios no additional steps are required - just pass the IQueryable to the Grid constructor. Check the server binding help topic for additional info.
For ajax binding scenarios the ToDataSourceResult extension method must be used to perform the data processing. Check the ajax binding help topic for additional information. If your model does not implement IQueryable custom binding should be implemented. This means that the developer is responsible for paging, sorting, filtering and grouping the data. More info can be found in the custom binding help topic.
Important:
All data operations will be performed at database server level if the underlying IQueryable provider supports translation of expression trees to SQL. Kendo Grid for ASP.NET MVC has been tested with the following frameworks:
Entity Framework
Linq to SQL
Telerik OpenAccess
NHibernate
.Columns(columns =>
{
columns.Bound(p => p.ID).Title("ID").Width(100).Visible(false);
columns.Bound(p => p.Apply).Title("Apply").Width(100);
columns.Bound(p => p.TaxName).Title("Tax Name").Width(100);
columns.Bound(p => p.TaxPercent).Title("Percent").Width(130);
columns.Bound(p => p.OrderApplied).Title("Oreder Applied").Width(130);
columns.Bound(p => p.Compund).Title("Compund").Width(130);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Pageable()
.Sortable()
.Scrollable(scr=>scr.Height(430))
//.Scrollable(scrollable => scrollable.Virtual(true))
.HtmlAttributes(new { style = "height:430px;" })
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.ID))
.ServerOperation(false)
.Create(update => update.Action("EditingInline_Create", "Taxes"))
.Read(read => read.Action("EditingInline_Read", "Taxes"))
.Update(update => update.Action("EditingInline_Update", "Taxes"))
.Destroy(update => update.Action("EditingInline_Destroy", "Taxes"))
)
)
Maddening... Trying to utilize AJAX reads with a Kendo Grid. I've done quite a few binding to data passed down from the model. I copy the code straight from the KendoUI site and tweak to meet my demands:
#(Html.Kendo().Grid<FaultReport2.Models.usp_CMC_TopIssues_Result>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.description).Title("Description");
columns.Bound(p => p.responsible).Title("Responsibility");
columns.Bound(p => p.charged_time).Title("Time");
columns.Bound(p => p.responsible).Title("Responsible");
columns.Bound(p => p.root_cause).Title("Root Cause");
columns.Bound(p => p.counter_measure).Title("Countermeasure");
columns.Bound(p => p.status).Title("Status");
})
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read
.Action("cmcTopIssues", "FaultInfo", new { equipment_id = Model.area_id, start_date = Model.start_date })
)
)
)
Controller code for the read.Action():
public ActionResult cmcTopIssues(int equipment_id, DateTime start_date)
{
var db = new Models.FAULTEntities1();
var top_issues = db.usp_CMC_TopIssues(equipment_id, start_date).ToList();
return Json(top_issues, JsonRequestBehavior.AllowGet);
}
Does not work. I verify that my cmcTopIssues method is being called and that the top_issues var is being filled. It just does not populate the grid.
When I switch over to local and pass the data down through the model, it works fine.
Any help would be appreciated.
Hmm, perhaps try modifying your action method as shown in here so that you return a Kendo data source result instead:
public ActionResult cmcTopIssues([DataSourceRequest]DataSourceRequest request, int equipment_id, DateTime start_date)
{
var db = new Models.FAULTEntities1();
var top_issues = db.usp_CMC_TopIssues(equipment_id, start_date).AsEnumerable();
return Json(top_issues.ToDataSourceResult(request));
}