I have same problem as Daniel had in this topic, but his solution doesn't work for me:
http://www.kendoui.com/forums/ui/grid/kendo-ui-grid-inserts-updates-create-duplicate-records.aspx#-jhxqRrNAUGsTFJaC-Ojwg
So use-case. Users adds 2 new records one after another:
Presses "Add new record" button of a grid
Fills the fields (name="Alex", amount=10, comment="first").
Record one is ready. Press 'Save'. (data goes to controller and than to Database)
User see one record in a grid
Press "Add new record" button again
Fills fields (name="Bob", amount=20, comment = "second").
Record one is ready. Press 'Save'. Data goes to controller and than to Database.
In this moment something happens and grid send Ajax request again with record one data to controller.
User updates grid and see three records
"Alex | 10 | first" (duplicated record) ID = 1
"Bob | 20 | second" ID = 2
"Alex | 10 | first" ID = 1
They recommend to return an ID for correct binding\update of data source with new record.
And I return it (new ID from database comes in response with bouns entity)! and this doesn't help.
Only if I add first record and refresh page with F5 and after that add second record everything is ok. But if add another one, the third records - problems appears again
Code in controller:
[HttpPost]
public JsonResult Create(BonusDto bonusDto)
{
BonusAggregate bonus;
if (bonusDto.Amount <= 0)
throw new ArgumentOutOfRangeException("Amount should be more than 0");
if (bonusDto.EmployeeId <= 0)
throw new ArgumentNullException("You should specify an existing employee");
using (var dbContext = new DatabaseContext())
{
BonusesRepository = new BonusesRepository(dbContext);
var employeeRepository = new EmployeesRepository(dbContext);
bonus = new BonusFactory(employeeRepository).Create(bonusDto);
BonusesRepository.Save(bonus);
}
HttpContext.Response.StatusCode = (int)HttpStatusCode.Created;
return Json(bonus); // try to return ID after bonus was saved
}
UI Code
// creates bonuses grid control
$("#bonusesGrid").kendoGrid({
dataSource: bonusesDataSource,
toolbar: ["create"],
editable: "inline",
columns: [
"BonusId",
"EmployeeId",
{
field: "EmployeeLastName",
editor: employeeAutocompletingEditor,
template: "#=EmployeeLastName#"
},
"Amount",
{
field: "Comment",
titel: "Comment",
editor: textareaEditor,
filterable: {
operators: {
number: {
contains: "Contains"
}
}
}
},
{
command: ["edit"],
title: " "
}
],
save: function(e) {
if (newValueEmployeeId !== undefined &&
newValueEmployeeLastName !== undefined &&
newValueEmployeeLastName !== "") {
setNewValueEmployeeIdAndLastName(newValueEmployeeId, newValueEmployeeLastName);
gridDataSource.model.EmployeeId = newValueEmployeeId; // it's a hack to bind model and autocomplete control
gridDataSource.model.EmployeeLastName = newValueEmployeeLastName;
} else {
gridDataSource.model.EmployeeId = currentValueEmployeeId;
gridDataSource.model.EmployeeLastName = currentValueEmployeeLastName;
}
},
edit: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
},
cancel: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
}
});
Bonus data source:
// bind json result from /Bonuses/GetPagedJsonBonuses
var bonusesDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("GetPagedJsonBonuses", "Bonuses")",
type : "GET",
contentType: "application/json",
dataType: "json",
cache: false
},
create: {
url: "#Url.Action("Create", "Bonuses")",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation === "update" || operation === "create") {
// correct format for conversion
var d = new Date(options.Date);
options.Date = kendo.toString(d, dateFormat);
// updates the BonusDTO.EmployeeId with selected value
if (newValueEmployeeId !== undefined)
options.EmployeeId = newValueEmployeeId;
}
if(operation === "read") {
options.filter = setFormattedFilterDate(options.filter);
}
return options;
}
},
pageSize: 15,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
error: showErrorMessage,
schema: {
data: "Data", // PagedResponse.Data
total: "TotalCount", // PagedResponse.TotalCount
model: {
id: "BonusId", // Data
fields: {
EmployeeId: { type: "number" },
EmployeeLastName: {
type: "string",
editable: true,
nulable: false,
validation: { required: {message: "Employee's last name is required"}}
},
Date: {
type: "date",
editable: true,
nullable: false,
validation: {
required: { message: "Date is required to be set" }
}
},
Amount: {
type: "number",
editable: true,
nullable: false,
defaultValue: 1,
validation: {
required: { message: "Amount is required to be set" }
}
},
Comment: { type: "string", editable: true }
} // fields
} // model
}// schema
});
I haven't seen this problem in my code. I do however have a "complete" event handler on my create and update events that refreshed the grid - it may help you:
dataSource: {
type: "jsonp",
transport: {
read: UrlBase + "getAll",
update: {
url: UrlBase + "Update",
dataType: "jsonp",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
create: {
url: UrlBase + "create",
dataType: "jsonp",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: UrlBase + "destroy",
dataType: "jsonp",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
}
},
...
Yes, hamed is correct. Your "create" action result passes in the object from your model that is to be saved to your database. Have the INSERT in your data access layer return the newly created key ("ID") in the database. Use this key to now set the "ID" field on your model that's passed in to the action result and then passed back to the view as JSON. Now the grid should know it's just created this record and does not need to do anything more with it. Otherwise, the model object returns with the "ID" field set to 0 so the grid thinks it still needs to add this record.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Grid_Create([DataSourceRequest] DataSourceRequest request, MyObject obj)
{
if (obj != null && ModelState.IsValid)
{
obj.Id = _myService.Create(obj);
}
return Json(new[] { obj }.ToDataSourceResult(request, ModelState));
}
This error occur when you did not pass Primary key to view in read action.
Regards
An alternative to Quinton Bernhardt's complete event: bind the dataSource.read() to the kendo sync event.
I'm using kendo's C# MVC's html helpers which don't expose the sync event, so I had to modify it after setting up the grid.
On window load:
var grid = $("#GridName").data("kendoGrid");
grid.dataSource.bind("sync", function () {
$("#GridName").data("kendoGrid").dataSource.read();
});
The sync event fires after the save request has been completed. The dataSource.read() gets the latest from the server, including the id that was set server side.
I had a similar issue, did various trials but fixed with the following trial
Jquery
create: {
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../../ajax/ajaxGv.aspx/addstaff"
},
parameterMap: function (options, operation) {
if (operation == "create" && options.models) {
return JSON.stringify({ "oStaff": options.models });
}
VB.Net
'Adding Staff
<System.Web.Services.WebMethod()> _
Public Shared Sub addStaff(ByVal oStaff As Object)
Dim strJson As String = JsonConvert.SerializeObject(oStaff)
Dim lstStaff As List(Of Staff) = JsonConvert.DeserializeObject(Of List(Of Staff))(strJson)
Dim db As New LiveB2cDataContext
Try
db.Staff.InsertAllOnSubmit(lstStaff)
Next
db.SubmitChanges()
'Fix is that you need to return the objects you have added in the database back as json to kendo
strJson = JsonConvert.SerializeObject(lstStaff, Formatting.None)
WriteJson(strJson) ' Returning the objects added as json back to Kendo
Catch ex As Exception
ErrorLog(ex)
End Try
End Sub
Public Shared Sub WriteJson(strJson As String)
Try
HttpContext.Current.Response.Write(strJson)
HttpContext.Current.Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
HttpContext.Current.Response.SuppressContent = True
Catch ex As Exception
ErrorLog(ex)
End Try
End Sub
Fix is that you need to return the objects you have added in the database back as json to kendo
I'm not sure if this is part of your issue, but in your DataSource's schema model you specify that the ID is the field named "BonusId", but that field isn't specified in the array of fields.
I was having a simular issue.
I fixed it but making sure the id in the model is referring to a field:-
model: {
id: "Id",
fields: {
Id: { editable: false, type: "number" },
AnotherName: { editable: true, type: "string" },
AnotherId: { editable: true, type: "number" }
}
}
This may not solve the asker's problem, but hopefully might help someone with the same issue.
For us, this problem was being caused by errors being returned in JSON. Some required properties didn't have a value, but weren't related to the data we were displaying in the grid. Giving those properties a default value in the grid solved the issue.
You can view the JSON that's being returned by using Fiddler Web Debugging Tools.
Related
For examplpe I am fetching the record through Json and in success function am storing the return data in localstorage to use
Output Json like
[{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
It's returning as expected
but I can't populate the data in drop down, if i hard coded the same json it's working. Thanks in advance please help me to resolve.
$.ajax({
url: 'http://test.com',
//type: 'POST',
//data :Editorcontent,
success: function (data) {
let fieldes = JSON.parse(data)
localStorage.setItem('one',fieldes)
},
error: function () {
alert(url);
}
});
var selected = localStorage.getItem('one');
//selected = [{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
//selected = selected.replace('\'',"'");
console.log(selected);
var editor = {
ajax: '',
ajaxFiles: '',
struct: {
buttons: ['top', 'bottom'] // buttons
},
fields: [
{
label: "Branch Name",
name: "DefaultBranchID",
values: selected,
type: 'select'
},
{
label: "Country:",
name: "CountryID",
type: 'multiselect',
attrs: [
{'pattern': '^[A-Za-z0-9_]+$'}
]
},
"selected" is the variable am assigning
OutPut for Branch Nam Drop down :-O/p
I have an object (A) with a few properties, one of which is a LIST of abother type (B).
I have a Web API Action that takes in an A object as a parameter.
I am just testing that I can pass this object via JSON son I have a webform with some Javascript on it as follows.......
var tmpData = {
lid: "f8fdb980-ccb8-4a54-9b83-b73dd2d569ca",
aid: "8f6efc68-d747-42a4-b7d4-218951b66a97",
bid: "e9f5e5d2-5d3d-41ac-89dc-7586ec2a5286",
ps: []
};
tmpData['ps'].push({ "cid": "5a664dcc-8281-41f1-b81c-ae49499e12b8", "d": 5, "q": 2 });
tmpData['ps'].push({ "cid": "4e9a30e0-c741-4708-88d7-8db4941c17cc", "d": 10, "q": 2 });
var myJSON = JSON.stringify(tmpData);
//Call the action to get the list in JSON format
url = "http://localhost:64878/home/TakeTestBasketAddItemsRequest";
$.ajax({
url: url,
type: 'POST',
cache: false,
data: myJSON,
success: function (resultantData) {
var s = resultantData;
pResults.innerHTML = s;
}
});
This gets to the action OK and the object has 2 items in the "ps" property.
Howeverm the values in these 2 items are lost and I am left with zeros / uninitialised values.
Whay am I losing the values of the list items?
For clarity - here is my Action also.
[HttpPost]
public ActionResult TakeTestBasketAddItemsRequest(ECodeBasketRequest model)
{
try
{
var sb = new StringBuilder();
sb.AppendLine(String.Format("LocationBridgeId: {0}{1}", model.lid, Environment.NewLine));
sb.AppendLine(String.Format("ApplicationBridgeId: {0}{1}", model.aid, Environment.NewLine));
sb.AppendLine(String.Format("BasketId: {0}{1}", model.bid, Environment.NewLine));
foreach (var p in model.ps)
{
sb.AppendLine(String.Format("CategoryBridgeId: {2} Denomination: {0} Quantity: {1}{3}", p.d, p.q, p.cid, Environment.NewLine));
}
return Content(sb.ToString());
}
catch (Exception ex)
{
return Content(string.Format("Problem: {0}", ex.ToString()));
}
}
As I said, I am just testing at the moment so would love to get to the bottom of this. Thanks in advace,
Ant
Apologies all - but it seems I ommitted the content type....
contentType: "application/json"
It's misleading when some of the object is reconstruucted OK and the rest isn't....but hey ho - It's Friday and it's working..
Well hopefully it will help someone else out.......
So I now find that this works.....
$.ajax({
url: url,
type: 'POST',
cache: false,
**contentType: "application/json",**
data: myJSON,
success: function (resultantData) {
var s = resultantData;
pResults.innerHTML = s;
}
I have the following Select2 configuration.
$scope.select2Options = {
simple_tags: false,
placeholder : "Search for a language",
multiple : true,
contentType: "application/json; charset=utf-8",
minimumInputLength : 3,
ajax : {
url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
dataType : 'json',
data : function(term) {
return {
language : term
};
},
results : function(data, page) {
return {
results :
data.map(function(item) {
return {
id : item.id,
text : item.description
};
}
)};
}
}
};
This allows me to populate the select2 control properly.
However, an issue occurs when I use Ajax in order to post the whole form containing the tags (amongst other): the json array sent to the server contains objects with two properties named id and text whereas the server would require id and description.
see snippet from my json:
"languages":[{"id":46,"text":"Français"},{"id":1,"text":"Anglais"}]
Does select2 allow for changing the name of the text to something else?
Changing my js to the following sorted the issue:
function format(item) { return item.description; };
$scope.select2Options = {
simple_tags: false,
placeholder : "Search for a language",
multiple : true,
contentType: "application/json; charset=utf-8",
minimumInputLength : 3,
data:{ text: "description" },
formatSelection: format,
formatResult: format,
ajax : {
url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
dataType : 'json',
data : function(term) {
return {
language : term
};
},
results : function(data, page) {
return {
results :
data.map(function(item) {
return {
id : item.id,
description : item.description
};
}
)};
}
}
};
Notice: one has to use the Select2 top level attribute data.
Here's the bare minium of the configuration neccesary to use a custom id and text properties on ui-select2
$scope.clients: {
data: [{ ClientId: 1, ClientName: "ClientA" }, { ClientId: 2, ClientName: "ClientB" }],
id: 'ClientId',
formatSelection: function (item) { return item.ClientName; },
formatResult: function (item) { return item.ClientName; }
}
Select2 requires that the text that should be displayed for an option is stored in the text property. You can map this property from any existing property using the following JavaScript:
var data = $.map(yourArrayData, function (obj) {
obj.text = obj.text || obj.name; // replace name with the property used for the text
obj.id = obj.id || obj.pk; // replace pk with your identifier
return obj;
});
Documentation
I have the following code. When fetching the value selected, it works fine. But if I try put the selected value in any condition, it falters. the code crashes.
var onAcctMgrSelect = function (e) {
// access the selected item via e.item (jQuery object)
ddAMList = $("#ddAM").data("kendoDropDownList");
if (ddAMList.value() == "0")
$("#btnSearch").attr("class", "k-button k-state-disabled");
else
$("#btnSearch").attr("class", "k-button");
///alert(ddAMList.text());
checkValidData();
};
DropDownlist Code is as below:
function loadAccountManagers() {
$("#ddAM").kendoDropDownList({
change: onAcctMgrSelect,
dataTextField: "AcctMgrFullName",
dataValueField: "Id",
dataSource: {
schema: {
data: "d", // svc services return JSON in the following format { "d": <result> }. Specify how to get the result.
total: "count",
model: { // define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { validation: { required: true }, type: "int" },
AcctMgrFullName: { type: "string", validation: { required: true} }
}
}
},
transport: {
read: {
url: "../services/Prospects.svc/GetAccountManagers", //specify the URL which data should return the records. This is the Read method of the Products.svc service.
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "GET" //use HTTP POST request as the default GET is not allowed for svc
}
}
}
});
I'm basically trying to disable the submit button if the first item is selected (which is a blank item in my case with a value of '0').
Am I going wrong anywhere? Please help!
I have a question about extjs 4.
Below is my storeMsg
var storeMsg = this.getMessageStore();
storeMsg.load({
scope: this,
autoLoad: true,
params:{
read_conditions: Ext.JSON.encode({
"employee_rid": '7976',
"year" : '2013', //etos
"kind_holiday_rid" : '1',
"request_days" : '5'
})
},
callback: function(records, operation, success) {
// do something after the load finishes
console.log(records[0].get('remain'));
console.log(records[0].get('messages'));
}
});
and i take a json response like as
{"total":1,"success":true,"data":[{"status":"true","messages":"\u03a3\u03c9\u03c3\u03c4\u03cc \u03b1\u03af\u03c4\u03b7\u03bc\u03b1 \u03ac\u03b4\u03b5\u03b9\u03b1\u03c2","remain":"25"}]}
I want to take the field status from json (ex true) outside from storeMsg.load();
For example
var vstatus = Ext.StoreMgr.lookup(storeMsg).data.items[0].data.status
but i take message this vstatus is undefined
I have changed my variable (vstatus) of code :
var vstatus = Ext.StoreMgr.lookup(storeMsg).getProxy().getReader();
and I am taking and object like as
className "Ext.data.reader.Json"
and it has some attributes. An attribute is
jsonData
data
remain 25
status true
message "Is correct"
total 1
success true
and I give in
var vstatus = Ext.StoreMgr.lookup(storeMsg).getProxy().getReader().jsonData;
and I take this message (undefined).
Do you have any idea how take the value from jsonData.data.status = true;
tnx
and the fully code about store , proxy and reader is below
Ext.define('MHR.store.Message',{
extend : 'Ext.data.Store',
model : 'MHR.model.Message',
storeId : 'Message',
autoLoad : true,
proxy : {
type: 'ajax',
api: {
read : 'php/crud.php?action=check'
},
actionMethods: {
read : 'POST',
},
reader: {
type: 'json',
root: 'data',
rootProperty: 'data',
successProperty: 'success',
messageProperty: 'message'
},
extraParams : {
'read_conditions': ''
}
}
});
try with:
storeMsg.each(function(record) {
var status = record.get('status');
});