Ajax webmethod, returning JSOn data - c#

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

Related

How to send data object which contain upload files and string to controller using ajax?

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

How to send multiple data in single FormData object in Ajax?

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

Circular reference was detected while serializing an object of type

I am trying to fetch company data based on company id through ajax and fill the related textboxes with the received data. Company id is selected through ajax autocomplete. The code was working fine two days back and suddenly it started generating an error for only first two entries of autocomplete and for rest it is working fine. Can anyone point out the mistake in this. Thank you.
Error Details: "Message":"A circular reference was detected while serializing an object of type \u0027System.Data.Entity.DynamicProxies.Company_81625299B5B4D7A3375D55E48BE84921728B8D48335366DF8CA6844A8D10FF5D\u0027.","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n.
Below is my code:
function setCompanyData(pageurl, txtboxid, txtResultid) {
var temp = true;
var searchTbox = $jq14("[id$=" + txtboxid + "]");
var resultTbox = $jq14("[id$=" + txtResultid + "]");
searchTbox.autocomplete({
source: function (request, response) {
$jq14.ajax({
url: pageurl,
data: "{ 'SearchText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('*')[0],
val: item.split('*')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoSelect: true,
autoFocus: true,
select: function (e, i) {
// e.preventDefault();
searchTbox.val(i.item.label);
resultTbox.val(i.item.val).trigger('change');
temp = true;
// return false;
},
change: function (e, i) {
var cId = resultTbox.val();
if (isEmptyOrSpaces(cId)) {
// error
cId = 0;
searchTbox.val("").trigger('');
}
if (isEmptyOrSpaces(searchTbox.val())) {
// error
cId = 0;
resultTbox.val("").trigger('change');
}
getCompanyDetails(cId);
},
minLength: 0
}).focus(function () {
if (temp) {
$jq14(this).autocomplete("search", "");
temp = false;
}
});
searchTbox.autocomplete("widget").addClass("fixedHeight");}
function getCompanyDetails(cid) {
$jq14.ajax({
url: "/sw/adm/update-delete-company.aspx/GetCompanyData",
data: "{ 'cId': '" + cid + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
$("#messageBox").hide().slideDown();
setTimeout(function () {
$("#messageBox").fadeOut();
}, 5000);
},
success: function (result) {
$jq14('#cphMainLeft_txtAddress').val(result.d.CompanyAddress);
$jq14('#cphMainLeft_txtCountry').val(result.d.CompanyCountry);
$jq14('#cphMainLeft_txtCity').val(result.d.CompanyCity);
$jq14('#cphMainLeft_txtNewCompanyName').val(result.d.CompanyName);
$jq14('#cphMainLeft_txtEmail').val(result.d.CompanyEmail);
$jq14('#cphMainLeft_txtPanNo').val(result.d.CompanyPAN);
$jq14('#cphMainLeft_txtTinNo').val(result.d.CompanyTIN);
$jq14('#cphMainLeft_txtPhone').val(result.d.CompanyPhone);
$jq14('#cphMainLeft_txtPincode').val(result.d.CompanyPincode);
$jq14('#cphMainLeft_hfTxtCountry').val(result.d.CompanyCountry);
$jq14("#cphMainLeft_ddlCompanyType").val(result.d.CompanyType);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
C# Webmethod goes like:
[WebMethod]
public static Company GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord != null)
return companyRecord;
else
return new Company();
}
Thank you Ashokkumar M. Prajapati for providing the hint.
Instead of returning Company object from [WebMethod], I have converted the company object to Json string in code behind and returned it.
Here is my WebMethod:
[WebMethod]
public static string GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord == null)
companyRecord = new Company();
string s = string.Empty;
s = JsonConvert.SerializeObject(companyRecord,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return s;
}
Then I updated the success method of getCompanyDetails(cid) to:
success: function (result) {
res = JSON.parse(result.d);
$jq14('#cphMainLeft_txtAddress').val(res['CompanyAddress']);
$jq14('#cphMainLeft_txtCountry').val(res['CompanyCountry']);
$jq14('#cphMainLeft_txtCity').val(res['CompanyCity']);
$jq14('#cphMainLeft_txtNewCompanyName').val(res['CompanyName']);
$jq14('#cphMainLeft_txtEmail').val(res['CompanyEmail']);
$jq14('#cphMainLeft_txtPanNo').val(res['CompanyPAN']);
$jq14('#cphMainLeft_txtTinNo').val(res['CompanyTIN']);
$jq14('#cphMainLeft_txtPhone').val(res['CompanyPhone']);
$jq14('#cphMainLeft_txtPincode').val(res['CompanyPincode']);
$jq14('#cphMainLeft_hfTxtCountry').val(res['CompanyCountry']);
$jq14("#cphMainLeft_ddlCompanyType").val(res['CompanyType']);
}
and it worked wonderfully. Thanks again.

Auto-complete select multiple tags in asp.net

Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});

Datatable.js - not able to display data

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

Categories

Resources