I'm using jsgrid to create an editable table. i used the code from this demo. The only difference is im using mvc instead of web api.
Looking at the network, the controller returns the needed json data and jsgrid also shows the pagination stuff on the bottom of the table. However, the table is not being populated
Here's the html and javascript code
<div id="jsGrid"></div>
#section scripts {
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script>
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "get",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
},
updateItem: function (item) {
},
deleteItem: function (item) {
}
},
fields: [
{ name: "SKU", type: "text", width: 50 },
{ name: "PartNumber", type: "text", width: 100 },
{ name: "ProductLineName", type: "text", width: 50 },
{ name: "ProductLineId", type: "text", width: 50 },
{ name: "Deleted", type: "checkbox", sorting: false },
{ type: "control" }
]
});
</script>
Here's the relevant method in the controller
public async Task<ActionResult> Get()
{
var query = db.Products
.Select(p => new ProductDto()
{
PartNumber = p.PartNumber,
SKU = p.SKU,
ProductLineName = p.ProductLines.ProductLineName,
ProductLineId = p.ProductLineId,
Deleted = p.Deleted
});
var products = await query.ToListAsync();
return Json(products, JsonRequestBehavior.AllowGet);
}
Anyone know what i can do to display/bind the returned data to the table?
Change your loadData call because its not specifying what to do when ajax call is done.
Try to rewrite it like below :
controller: {
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "get",
dataType: "json",
data: filter
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
},
This is the client side javascript that I used which finally put some data in the grid: (just the controller part)
controller: {
loadData: function (filter) {
console.log("1. loadData");
return $.ajax({
type: "GET",
url: "/Timesheet/GetTimesheet/",
dataType: "json",
data: filter
console.log("3. loadData complete");
}
None of the posted explicit promise code functioned at all. Apparently $.ajax returns a promise.
and this was my MVC controller code that I called with ajax (C#):
public async Task<ActionResult> GetTimesheet()
{
int id = Convert.ToInt32(Session["UID"]);
var tl = (
from ts in db.Tasks
orderby ts.Task_Date descending
where ts.Emp_ID == id
select new
{
ID = ts.Task_ID,
Date = ts.Task_Date,
Client = ts.Customer_ID,
Hours = ts.Total_Hours
}
).Take(4);
var jsonData = await tl.ToListAsync();
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
There are no actual examples of required Json for jsGrid. anywhere but this worked for me - note no headers or anything.
Related
I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});
I'm using this library
https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.js">
I know there are a lot of examples out there and I've tried them all most recent:
var $client_id = $("#client_id").select2({
dropdownParent: $('#categoryForm'),
ajax: {
quietMillis: 300,
url: apiPath,
xhrFields: {
withCredentials: true
},
crossDomain: true,
type: "GET",
data: function (params) {
var queryParameters = {
search: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data.data, function (item) {
return {
text: item.client_name,
id: item.client_id
}
})
};
}
}
});
$client_id.val(6).trigger('change');
As you can see at the bottom I'm trying to select the value using the (valid) ID. I have been successfull using this method:
var option = new Option(data.customer_name, data.customer_id, true, true);
customerSelect.append(option).trigger('change');
But I'd rather just use the ID if it's possible
I have the following select2 ajax call. How do I use the jquery $.map() to parse the returned json results. From the users array i need to get the Text and Value results. From the pager array I need to get the TotalItemCount. What I have below doesnt seem to work i.e the search results don't seem to display in the select list. No console errors are shown either so I'm not sure what Im doing wrong.
var url = '#Url.Action("GetEmployees", "Employees")';
var pageSize = 20;
$(".js-data-example-ajax").select2({
ajax: {
url: url,
dataType: 'json',
delay: 250,
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data, function (users) {
return {
text: users.Text,
id: users.Value
}
}),
pagination: {
more: (params.page * pageSize) < data.pager.TotalItemCount
}
};
},
cache: true
},
minimumInputLength: 2,
placeholder: "-- Select --",
allowClear: true
});
The json returned is as follows:
{
"pager":{
"PageCount":1,
"TotalItemCount":1,
"PageNumber":1,
"PageSize":20,
"HasPreviousPage":false,
"HasNextPage":false,
"IsFirstPage":true,
"IsLastPage":true,
"FirstItemOnPage":1,
"LastItemOnPage":1
},
"users":[
{
"Disabled":false,
"Group":null,
"Selected":false,
"Text":"Joe Blogs",
"Value":"97306aa4-d423-4770-9b45-87a701146b10"
}
]
}
I was correct. I wasn't using the jQuery.map() correctly. It should be as follows:
results: $.map(data.users, function (users) {
return {
text: users.Text,
id: users.Value
}
}),
i have problem with Kendo data grid component.
I'm trying to add new row into grid and create remote request to API via create event.
Problem is that if i try to add new row after first request Kendo make 2 requests instead of the one.
I tried to find some solution for this using transport create and options.success method but without luck.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-transport.create
Could somebody tell to me what i'm doing wrong?
Thanks for any help.
Here is the code of the server response for create:
+ Response 200 (application/json)
{
"status": "OK",
"result":[
{
"id":22,
"username":"blahblah",
"name":"Thomas",
"surname":"Man",
"email":"to.mas.marny#gmail.com",
"created":"1399986964",
"role":"USER"
}
]
}
Here is the code of the method:
$scope.initGrid = function () {
// get access token from localstorage
var token = localStorage
.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token": token,
"data": {
"page": 1,
"items_per_page": 20
}
};
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type: "POST",
data: JSON
.stringify(paginationData),
success: function (
response) {
console
.log("List of users succesfully obtained");
console
.log(response.result);
// pass response to
// model
options
.success(response);
// $notification.enableHtml5Mode();
},
error: function (error) {
console
.log("user list request error");
console.log(error);
$notification
.error(
"User list cannot be loaded",
"Please try again in a minute.");
}
});
},
update: function (options) {
console.log("Update");
options
.success("{\"test\":\"test\"}");
},
destroy: function (options) {
console.log("destroy");
options
.success("{\"test\":\"test\"}");
},
create: function (options) {
console.log("Create");
console.log(options.data);
$.ajax({
url: $rootScope.apiBaseUrl + "user/create",
dataType: "json",
type: "POST",
data: JSON
.stringify(options.data),
success: function (
response) {
console
.log("New user created");
console
.log(response.status);
// pass response to
// model
options
.success(response.result);
// $notification.enableHtml5Mode();
},
error: function (error) {
console.log("user list request error");
console.log(error);
$notification
.error(
"User cannot be created",
"Please try again in a minute.");
}
});
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
//batch : true,
//autoSync: true,
schema: {
data: "result",
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true
},
name: {
editable: true,
nullable: false
},
username: {
editable: true,
nullable: false
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataPacket,
filterable: true,
pageSize: 20,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id", "name", "username", {
command: ["edit", "destroy"],
title: " ",
width: "200px"
}],
editable: "inline"
});
};
If you declare id inside model then you don't have to declare id inside model fields.
Also when you point
data: "result"
for the model you have to pass
options.success(response)
inside ajax's success function, not just
options.success(response.result)
I think if null is passed to the Datasource of the kendo Grid in the html helper, the Grid will be built in “remote data mode” rather than “local data mode”
and since the read Url is not set the current browser Url will be used for the read operation.
make sure to initialize the list in the Model before using it as a Datasource.
i have a kendo ui grid with asp web api as backend. When i call the create method in the kendo ui, it's called the following method in web api
public IHttpActionResult PostProduct(ProductDTO product)
{
...
...
return StatusCode(HttpStatusCode.NoContent);
}
Now if i try to edit the item in the Kendo Ui Grid is called again the create method instead of the update method.
If i reload the page (so is called the read method of kendo ui grid), the update method works.
What's the problem? I have the following schema:
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, type: "number" },
Name: { validation: { required: true } },
Description: { editable: true },
Price: { editable: true },
Active: { type: "boolean" },
}
}
}
I have the following transport (omitted some code)
$scope.tabellaProdotto = new kendo.data.DataSource({
transport: {
read: {
url: function () {
return "api/Prodotti/GetProdottoPerTipoProdotto/" + productTypeMainSelected;
},
dataType: "json"
},
create: {
url: "api/Prodotti/PostProdotto",
dataType: "json",
data: function (prodottoTmp) {
...
},
type: "POST"
},
update: {
url: function (prodotto) {
return "api/Prodotti/PutProdotto" + prodotto.Id
},
data: function (prodottoTmp) {
...
},
type: "PUT",
dataType: "json"
UPDATE: the problem seems be the return of the web api action method:
return CreatedAtRoute("DefaultApi", new { id = p.Id }, p);
Now works but the p object size dimension is very high: i must return the entire object?
This sounds like the Grid is not getting the Json back in the right format.
Be sure to use the KendoMVC DataSourceRequest Object to return data in the right format.
Here is an example:
public ActionResult Update([DataSourceRequest] DataSourceRequest request, MyViewModel data)
{
var result = UpdateBackend(data);
return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}