Kindo Grid in MVC is displaying raw data - c#

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.

Related

I want to call Action Method of controller and return View on Kendo grid row click

Below is my kendo grid code
#(Html.Kendo().Grid<DataSource>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Quote_ID).Filterable(false);
columns.Bound(p => p.Ticket_ID).Groupable(true);
columns.Bound(p => p.Channel).Groupable(true);
columns.Bound(p => p.Agent_Alias).Groupable(true).Hidden(true);
columns.Bound(p => p.Shipping_Carrier).Groupable(true).Hidden(true);
columns.Bound(p => p.Quote_ID).Title("View
Details").Groupable(false)
.Template(#<text>
#Html.ActionLink("Show Product Details", "GridRowSummary",
"GridOrderSummary")</text>);
})
From ActionLink I am trying to call Action Method of my controller.
Below My controller code
public ActionResult GridRowSummary()
{
return View();
}
Using Template will work when using Ajax bound grids e.g:
columns.Template(c => #Html.ActionLink("GridRowSummary", "GridOrderSummary", new { id = c.Id, }));
If not using Ajax bound grids use ClientTemplate attribute on the column, along with a method to display the associated data, if required e.g.:
columns.Bound(p => p.Quote_ID).Title("View Details").Groupable(false)
.ClientTemplate(#Html.ActionLink("#=Quote_ID#", "GridRowSummary", new { ID = "#=ID#" }).ToHtmlString());
There is a third method (a little messy) which allows you to add custom buttons/icons etc e.g:
columns.Bound(p => p.Quote_ID).ClientTemplate("<a href='" + #Url.Action("GridRowSummary", "GridOrderSummary", new { id = "#=Id#" }) + "' class='btn btn-primary'><i class='fa fa-eye'></i> Link</a>" );
EDIT
From looking through the FAQ section, found an even neater solution where you can pass controller name and your Quote_ID parameter (although this way does involve setting up a Javascript function):
columns.Bound(p => p.Quote_ID).ClientTemplate("#= getDetails(data) #");
<script>
function getDetails(data) {
var action = '#Url.Action("NameOfMethod", "NameOfController")';
var html = kendo.format("<a href='{0}/{1}'>Link</a>",
action,
data.Quote_ID
);
return html;
}
</script>
For client template below code works. Replace is necessary.
columns.Bound(p => p.Quote_ID).Title("View Details").Groupable(false)
.ClientTemplate(
#Html.ActionLink("#=Quote_ID#", "Summary", new { Quote_ID = "Id"
}).ToHtmlString().Replace("Id", "#=Quote_ID#"));
This solution works for me.
.Events(events =>
{
events.Change("onRowSelected");
})
function onRowSelected(e) {
debugger;
var gview = $("#grid").data("kendoGrid");
//Getting selected item
var selectedItem = gview.dataItem(gview.select());
var ticketId = selectedItem["Ticket_ID"];
window.location.href = "/GridOrderSummary/GridRowSummary?
ticketId=" + ticketId;
}
//Controller code
public class GridOrderSummaryController : Controller
{
// GET: GridOrderSummary
public ActionResult GridRowSummary(string ticketId)
{
// your code
return View();
}
}

Kendo UI MVC - Grid Paging, Sorting, Refreshing not working with WebAPI binding

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.

dropdownlist in kendo grid not working

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.

Kendo MVC Ajax Grid : Values are not showing

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.

Kendo Grid - Won't bind to remote data MVC

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));
}

Categories

Resources