I am not able to retrieve data in datatable using datatable.js. The Json response is a string but in the output I get every character of the string in each row rather that jst two entries.
Please help. Thanks in advance
function fillGrid() {
$.ajax({
type: 'POST',
url: 'BehindCode/client.aspx/fillgrid',
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#gridLoadingDiv').attr('style', 'display:block');
},
complete: function () {
$('#gridLoadingDiv').attr('style', 'display:none');
},
data: "{}",
success: function (data) {
data = data.d;
alert(data);
$("#clientTable").DataTable({
"searching": true,
"processing": true,
"data": data,
"columns": [{
"title": "CLIENT NAME"
}]
});
}
});
}
C# code..from where data is being retreived..
[WebMethod]
public static string fillgrid()
{
BehindCode_client client = new BehindCode_client();
string strfetch = "SELECT CLIENT_NAME FROM k_client_master";
string aadata = "";
client.ds = client.DEngine.GetDataSet(strfetch, "Data", client.conn);
if (client.ds != null && client.ds.Tables[0].Rows.Count > 0)
{
aadata = JsonConvert.SerializeObject(client.ds);
// aadata = "{'draw':1, 'recordsTotal':2, 'recordsFiltered':2, 'data':[{'CLIENT_NAME': 'Pyrotech'},{'CLIENT_NAME':'Workspace'}]}"; // tried this also
// aadata = "{'data':[{'CLIENT_NAME': 'Pyrotech'}, {'CLIENT_NAME':'Workspace'}]}"; // tried this as well
}
return (aadata.Replace("'","\""));
}
}
JSON Response as in developer tools
Output in datatable
enteries in database which are retreived
I'm not familiar with C# but on the JavaScript part you're not decoding the JSON data.
Try this:
success: function (data) {
data = JSON.parse(data.d).Data;
alert(data);
$("#clientTable").DataTable({
"searching": true,
"processing": true,
"data": data,
"columns": [
{data: "CLIENT_NAME"}
]
});
}
Related
I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}
Getting error while implementing Kendo Grid inline edit CRUD. When I add a new record and update it, I receive response code 500 with error:
I believe the problem is coming from parameterMap. What is the correct way to pass the model to the controller in Kendo?
Invalid JSON primitive: models.
What are the models?
Source Code:
$(document).ready(function () {
var baseUrl = "/SomeUrl",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: baseUrl + "/GetAccolades?profileId=" + #profileId,
type: "GET",
dataType: "json"
},
create: {
url: baseUrl + "/AddAccolade",
type: "POST",
dataType: "json",
contentType: "application/json",
},
update: {
url: baseUrl + "/UpdateAccolade",
type: "PUT",
dataType: "json",
contentType: "application/json",
},
delete: {
url: baseUrl + "/DeleteAccolade",
type: "DELETE",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
alert(kendo.stringify(options.models));
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
schema: {
model: {
id: "ProfileAccoladeID",
fields: {
ProfileAccoladeID: { editable: false, nullable: false },
ProfileID: { editable: false, nullable: false, defaultValue: #profileId },
Years: { type: "string" },
Name: { type: "string" },
Level: { type: "string" },
Event: { type: "string" },
}
}
}
});
$("#accolades-grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: ["create"],
columns: [
{ field: "Years", width: "150px" },
{ field: "Name", title: "Name", width: "150px" },
{ field: "Level", title: "Level", width: "150px" },
{ field: "Event", title: "Event", width: "450px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "inline"
});
});
</script>
Controller method:
[HttpPost]
public JsonResult AddAccolade(ProfileAccolade accolade)
{
using (var db = new XXXEntities())
{
if (accolade != null)
{
var newAccolade = new ProfileAccolade()
{
ProfileID = accolade.ProfileID,
Years = accolade.Years,
Name = accolade.Name,
Level = accolade.Level,
Event = accolade.Event
};
db.ProfileAccolades.Add(newAccolade);
db.SaveChanges();
return Json(new { Success = true });
}
else
{
return Json(new { Success = false, Message = "Error occured" });
}
}
}
How do I fix this error?
Update:
By removing contentType: "application/json", the error Invalid JSON primitive: models. is gone. However, the controller does not get the model.
Any ideas to fix this?
The problem originated by usage of contentType: "application/json" inside both transport.create and transport.update part of kendo.data.DataSource. Since both operations use AJAX call (i.e. jQuery.ajax() method), the contentType setting affects how type of request body will send.
By setting "application/json" content type, the request body will treated as JSON content, but actually transport.parameterMap returns URL encoded version containing models and formatted JSON string as key-value pair (KVP). This is why "Invalid JSON primitive" error occurs, because URL encoded format is not same as JSON format.
If you wish to keep "application/json" setting for AJAX call, add JSON.stringify method to convert URL encoded format of models as JSON data:
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return JSON.stringify({ models: kendo.stringify(options.models) });
}
}
However if you want to send parameterMap as default content type (application/x-www-form-urlencoded), just remove all contentType definitions to set it back:
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: baseUrl + "/GetAccolades?profileId=" + #profileId,
type: "GET",
dataType: "json"
},
create: {
url: baseUrl + "/AddAccolade",
type: "POST",
dataType: "json"
},
update: {
url: baseUrl + "/UpdateAccolade",
type: "PUT",
dataType: "json"
},
delete: {
url: baseUrl + "/DeleteAccolade",
type: "DELETE",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
alert(kendo.stringify(options.models));
return { models: kendo.stringify(options.models) };
}
}
},
// other DataSource definitions
});
Reference:
kendo.data.DataSource (Kendo UI Documentation)
My application has multiple data like Text-box value, label value, Drop-Down value,File Data and send same data at server side and store in database
To achieve this, i have used below method but now i want to use Formdata and append each value and send it to server side
How to achieve this scenario using Formdata with specific object type.
Below is the code
var selectedText = $('#Commentinput').text();
$('#actioncomments').text(selectedText);
var debitEntityValue = $('#DrAccount option:selected').text();
var creditEntityValue = $('#CrAccount option:selected').text();
var amount = $("#Amountinput").val();
var paymentActionReason = $('#action').text();
var paymentCommentReason = $('#Commentinput').val();
var prepayAccountId =#Model.prepaidBranchList.PrepaidID;
var transactionDate = '#DateTime.Today';
var transactionExtensions = "1";
var fileBase64Data = $("#fileUpload").text();
if ($('#Commentinput').val() == "") {
paymentCommentReason = "No Comment";
}
else {
paymentCommentReason = $('#Commentinput').val();
}
var adjustmentTransactioninfo =
{
PaymentReasonMasterId: paymentReasonMasterId,
DebitEntityValue: debitEntityValue,
CreditEntityValue: creditEntityValue,
Amount: amount,
PaymentActionReason: paymentActionReason,
PaymentCommentReason: paymentCommentReason,
PrepayAccountId: prepayAccountId,
TransactionDate: transactionDate,
TransactionExtensions: transactionExtensions
};
var data = JSON.stringify({
'adjustmentTransactioninfo': adjustmentTransactioninfo,
'fileData': 0
});
var url = "#Html.Raw(Url.Action("AdjustmentTransaction",
"PrepaidActivity"))";
url += '?branchCode=' + '#Model.prepaidBranchList.IASBranchCode'
$.ajax({
url: url,
traditional: true,
data: data,
enctype:"multipart/form-data",
contentType: "application/json charset=utf-8",
dataType: "json",
type: 'POST',
success: function (data) {
$("#ajaxLoader").show();
if (data != null) {
var ProductActionID = data.SuccessMessage.split(':');
uploadFile.append('ProductActionID' , ProductActionID[1]);
FileUpload(uploadFile);
var dialog = document.querySelector('#Finaldialog');
var ConfirmationScreen = $("<p></p>").text(data.SuccessMessage);
$("#finalmdl-dialog").append(ConfirmationScreen);
dialog.showModal();
dialog.querySelector('button:not([disabled])').addEventListener('click', function() {
dialog.close();
location.reload();
});
}
}
});`
Controller code
public JsonResult AdjustmentTransaction(TraxAdjustmentTransactionInfo adjustmentTransactioninfo, string fileData, string branchCode)
{
PrepaidAdminService.PrepaidAdminDashBoardServiceClient _PrepaidAdminService = new PrepaidAdminService.PrepaidAdminDashBoardServiceClient();
TraxAdjustmentTransactionResult result;
adjustmentTransactioninfo.ProductActionMasterId = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["ProductActionMasterId"]);
adjustmentTransactioninfo.ProductCode = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ProductCode"]);
adjustmentTransactioninfo.DebitEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.CreditEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.UserId = Utility.UserID;
adjustmentTransactioninfo.RetailerId = _PrepaidAdminService.GetBranchRetailerId(branchCode);
use serializeArray and can be add the additional data:
var data = $('form').serializeArray();
data.push({name: 'Amit', value: 'love'});
$.ajax({
type: "POST",
url: "url",
data: data,
success: function(data) {
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
Remove the #Html.Raw(Url.Action()), contentType and JSON.stringify() and leave that to the ModelBinder. Change your ajax to this:
$.ajax({
url: '#Url.Action("AdjustmentTransaction", "PrepaidActivity")',
traditional: true,
data: {
adjustmentTransactioninfo: adjustmentTransactioninfo,
fileData: "0",
branchCode: '#Model.prepaidBranchList.IASBranchCode'
},
enctype: "multipart/form-data",
type: 'POST',
success: function (data) {
alert("success");
}
});
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
// Param1 and param2 name should be same as method argument
I am having some issues with a Webmethod (c#) populating a JQuery DataTable table with JSON data.
Ajax call:
function loadTable(message) {
$.ajax({
type: "POST",
url: "TestBed.aspx/ValueDateSummary",
cache: false,
data: JSON.stringify({ senderBIC: senderBIC }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var data = msg.d;
alert(data["counter"]);
alert(data);
alert(typeof msg);
var otable = $("#test").dataTable({
// "sAjaxDataProp": msg.d,
"aoColumns": [
{ "mDataProp": "counter" },
{ "mDataProp": "SessionID" },
{ "mDataProp": "MsgType" }
]
});
}
});
};
No errors, but the datatable is empty.
Here are the results of the alerts
alert(data["counter"]) = UNDEFINED
alert(data) = [{"counter":3,"SessionID":"1","MsgType":"103","ValueDate":"2007-08-01","Sender":"1"}, {"counter":7,"SessionID":"2","MsgType":"103","ValueDate":"2009-05-26","Sender":"2"}]
alert(typeof msg) = OBJECT
any ideas why my table is empty?
* EDIT *
THIS IS THE FINAL SUCCESS METHOD WHICH WORKED
success: function (msg) {
var data = JSON.parse(msg.d);
$("#test").dataTable({
"aaData": data,
"aoColumns": [{
"mDataProp": "counter"
}, {
"mDataProp": "SessionID"
}, {
"mDataProp": "MsgType"
}]
});
}
You are never settings the data of the oTable...
You have to give it an Array of Arrays (var object = [][]):
You can either do it as ajax and put your $ajax code into the fnServerData function
Or do the following: (taken from example from DataTables)
function loadTable(message) {
$.ajax({
type: "POST",
url: "TestBed.aspx/ValueDateSummary",
cache: false,
data: JSON.stringify({
senderBIC: senderBIC
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var data = [];
$.map(msg.d, function (item) {
{
var row = [];
row.push(
item.counter,
item.SessionID,
item.MsgType
//Commented out because you didn't include them in your aoColumns declaration, if you want them in the table to access later just make them non-visible.
//item.ValueDate,
//item.Sender
);
data.push(row);
}
});
var otable = $("#test").dataTable({
"aaData": data,
"aoColumns": [
{"mDataProp": "counter"},
{"mDataProp": "SessionID"},
{"mDataProp": "MsgType"}
]
});
}
});
}
As of jQuery DataTables 1.7.2 you can use array of objects as a data source but only with the ajax source (sAjaxSource) and it is slightly slower because it just manually copies it to an array or arrays.
Try changing your success function to the following:
var data = msg.d;
alert(data["counter"]);
alert(data);
alert(typeof msg);
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push([
data[i].counter,
data[i].SessionID,
data[i].MsgType,
data[i].ValueDate,
data[i].Sender
]);
}
var otable = $("#test").dataTable({
"aaData": rows
});
I can successfully make the AJAX call to my web method using the following code and web method return the JSON which is pasted below:
My Web Method
[WebMethod]
public static string GetJson()
{
string query = "SELECT top 10 cast(ClientUID as varchar) ClientUID FROM <tablename>";
SqlCommand cmd = new SqlCommand(query);
// Populate the DataSet.
DataSet data = GetData(cmd);
// return the Customers table as JSON.
DataTable dt = data.Tables[0];
var returnJSON = (from p in dt.AsEnumerable()
select new
{
ClientUID = p.Field<string>("ClientUID")
}).ToList();
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(returnJSON);
return json;
}
JSON returned by web method:
[{"ClientUID":"1"},{"ClientUID":"2"},{"ClientUID":"3"},{"ClientUID":"4"},{"ClientUID":"5"},{"ClientUID":"6"},{"ClientUID":"7"},{"ClientUID":"8"},{"ClientUID":"9"},{"ClientUID":"10"}]
Call to web method using AJAX
<script type="text/javascript">
$(document).ready(function() {
$.ajax(
{
type: "POST",
url: "ServeClientCalls.aspx/GetJson",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
//checking the content return from the above web method
$("#msg").html(msg.d);
//Binding to kendo Grid
$("#grid").kendoGrid({
dataSource: {
data: msg.d,
schema: {
model: {
fields: {
ClientUID: { type: "string" }
}
}
},
pageSize: 20
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "ClientUID" }
]
});
},
error: function(x, e) {
$("#msg").html(x.responseText);
}
});
});
</script>
Problem : My grid does not bind and only headers are displayed whereas when I use the code in this manner mentioned below it is working
<script type="text/javascript">
$(document).ready(function() {
$.ajax(
{
type: "POST",
url: "ServeClientCalls.aspx/GetJson",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
//checking the content return from the above web method
$("#msg").html(msg.d);
**var p = [{ ClientUID: 1 }, { ClientUID: 2 }, { ClientUID: 3 }, { ClientUID: 4 }, { ClientUID: 5 }, { ClientUID: 6 }
, { ClientUID: 7 }, { ClientUID: 8 }
, { ClientUID: 9 }, { ClientUID: 10}];**
//Binding to kendo Grid
$("#grid").kendoGrid({
dataSource: {
**data: p,**
schema: {
model: {
fields: {
ClientUID: { type: "string" }
}
}
},
pageSize: 20
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "ClientUID" }
]
});
},
error: function(x, e) {
$("#msg").html(x.responseText);
}
});
});
</script>
Use data: "d", under schema section. That should work.