Not able to access JSON datas - c#

I am trying to loop through the JSON object and create an input type dynamically in a div
here is the Jquery function
$(document).ready(function (){
$.ajax({
type: "POST",
url: "Tables.aspx/TotaTable",
contentType: "application/json; charset=utf-8",
dataType:'JSON',
success: function(data) {
//var data= $.parseJSON(data);
$.each(data,function(index,jsonobj)
{
alert(jsonobj.OTID);
}
);
}
});
});
Here is the server side code that return the JSON values
I am using json.net framework to convert my datatable to JSON
[System.Web.Services.WebMethod(EnableSession=true)]
public static string TotaTable()
{
LoginData lData = (LoginData)HttpContext.Current.Session["LData"];
ClsDataAccess cData = new ClsDataAccess();
DataTable dt = cData.GetTable("Select otid,ottableno from FBOUTLETTABLES where otoutletid=1");
string val=JsonConvert.SerializeObject(dt).ToString();
return val;
}
here is the JSON value that is sent to the client side
[{"OTID":76.0,"OTTABLENO":222.0},{"OTID":3.0,"OTTABLENO":3.0},{"OTID":4.0,"OTTABLENO":4.0},{"OTID":5.0,"OTTABLENO":5.0},{"OTID":6.0,"OTTABLENO":6.0},{"OTID":7.0,"OTTABLENO":7.0},{"OTID":8.0,"OTTABLENO":8.0},{"OTID":9.0,"OTTABLENO":9.0},{"OTID":2.0,"OTTABLENO":2.0},{"OTID":1.0,"OTTABLENO":1.0}]
My problem is
alert(jsonobj.OTID);
shows 'undefined'
I did try changing the server side function to return a List
like
public static List<Tables> Tables()
{
List<Tables> myList=new List<Tables>();
//Code to get datas from the database
foreach(DataRow row in dt.Rows)
{
myList.Add(new Tables{
tabID=row["tabID"].ToString();
tables=row["tab"].ToString();
});
}
return myList;
}
but I am facing the same issue..

Finally Got It working
Here is the Jquery Code
var obj={};
obj.ID=id;
$.ajax({
type:"POST",
url:"Tables.aspx/ItemsFromCategory",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType:'json'
}).done(function(res) {
var resultAsJson = res.d;
$.each(resultAsJson, function (index, resObject) {
alert(resObject.ID);
});
}
});
I did also change the server side code to this
public static List<ItemClass> ItemsFromCategory(string ID)
{
LoginData lData = (LoginData)HttpContext.Current.Session["LData"];
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
List<ItemClass> myList = new List<ItemClass>();
if (lData != null)
{
ClsDataAccess cData = new ClsDataAccess();
DataTable dt = cData.GetTable("Select itmid,ITMNAME from FBITEMDETAILS where itmtype='I' and itmisprimary='N' and itmoutletid=" + lData.fbOutLetid + " and itmgrpid=" + ID);
// DataTable dt = cData.GetTable("Select itmid,ITMNAME from FBITEMDETAILS where itmtype='I' and itmisprimary='N' and itmgrpid=" + ID);
foreach (DataRow row in dt.Rows)
{
myList.Add(new ItemClass
{
ID = row["itmid"].ToString(),
itemName=row["ITMNAME"].ToString(),
});
}
// result = ser.Serialize(myList);
// return result;
return myList;
}
// return string.Empty;
return myList;
}

Related

Ajax Gives Random Result while trying to bind table in ASP.Net

i am trying to populate html table from database c# and jquery AJax.But while i run it. it gives sometime success and some time Undefined And Sometime Blank Alert Box by while i pass same parameter every time.And When It Success It Bind Table But this table couln't hols on page it shows but disappear at once.
Here Is My Code:
C# Code
[WebMethod]
public static Report[] databind(string srh)
{
List<Report> list1 = new List<Report>();
try
{
DataTable dt = SQLDatabaseManager.ExecuteDataTable("select *,convert(nvarchar,IssueDate,106) as Idate,convert(nvarchar,ValidDate,106) as Vdate,convert(nvarchar,NextAuditDate,106) as Ndate from [Staun_Icrtms].[tbl_Clients] where Org_name like '%" + srh + "%' order by Org_name desc ");
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
Report data1 = new Report();
data1.orgName = dr["org_name"].ToString();
list1.Add(data1);
}
}
return list1.ToArray();
}
catch (Exception ex)
{
return list1.ToArray();
}
}
}
Jquery Ajax
function DataBind() {
debugger;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "ClientReport.aspx/databind",
data: "{srh:" + JSON.stringify($('#txtName').val()) + "}",
dataType: 'json',
success: function (data)
{
if (data.d.length > 0) {
alert('Success')
for (var i = 0; i < data.d.length; i++) {
$('#tblClient').append('<tr><td>' + data.d[i].orgName + '<td><tr/>');
}
}
},
error: function (xhr)
{
alert(xhr.responseText);
}
})
}

Failed to load resource on web method AJAX

I'm trying to use AJAX and calling web method like this in my code.
function generate_source(year_source, month_source) {
var gData_source = '';
if (year_source) {
gData_source = [];
gData_source[0] = year_source;
gData_source[1] = month_source;
console.log('first part');
}
else {
var d_source = new Date();
gData_source = [];
gData_source[0] = d_source.getFullYear();
gData_source[1] = d_source.getMonth() + 1;
console.log('second part');
}
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
var ctx = document.getElementById("order_source").getContext('2d');
$.ajax({
url: "dashboard.aspx/getordersource",
data: jsonData_source,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#loader_divsource").show();
},
success: function (response) {
$("#loader_divsource").hide();
var chartLabel = eval(response.d[0]); //Labels
var chartData = eval(response.d[1]); //Data
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: chartLabel,
datasets: [
{
type: 'doughnut',
label: chartLabel,
data: chartData,
backgroundColor: [
"#FF6384",
"#36A2EB",
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
]
}
]
}
});
}
});
}
var d_source = new Date();
gData_source = [];
$('#year_source').val(d.getFullYear());
$('#month_source').val(d.getMonth() + 1);
generate_source('', '');
My web method is like this;
[System.Web.Services.WebMethod]
public static List<string> getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
var returnData = new List<string>();
......
return returnData;
}
Whenever I try to run this data, my breakpoint for the web method is not hit. Further, if i use the same method without data, i don't get this error. It's driving me crazy.
I think your problem is in this code :
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
you are trying to serialize array with key value pair that it is become invalid.
change to this :
var jsonData_source = JSON.stringify(gData_source);
also your web method should be like this :
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.JSON)]
// just return a string, not list, your JSON string should have contain all your enumerable in your string Data
public static string getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
JsonSerializer serializer = new JsonSerializer();
var returnData = serializer.serialize(ds);
......
return returnData;
}
Hope it helps.

Textbox autocomplete by json

I am having problem while passing json data to the source of autocomplete multiselect jquery
this is the jason data which i am sending
[ "abhinav#sdv.com","nishimura#dscs.com","alex#sds.com","alice#sdvs.com","amit#sds.com"]
autocomplete: {
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/CommanService.asmx/ExtractEmail",
data: {},
dataType: "json",
success: function (data) {
var vServiceData = eval(data);
// alert(data.d[0].data123);
//return eval('[' + data.d + ']');
//response(vServiceData);
// alert(data);
response(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
})
}
in this source of ajax but the problem here is that istead of getting these record in
diffrent string the output is in the form of single string but when i pass static data like
source=["Red","blue","green"]
MY webservice code is
#region(EXTRACT EMAIL)
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string ExtractEmail()
{
//Webservice is used to extract the employee data
VisualLibrarySoapClient oVisualLibrary = new VisualLibrarySoapClient();
string data = oVisualLibrary.EmployeeSelectData();
DataSet ds = new DataSet();
ds = GetDataSet(data);
//Used data columns to extract email from data set
DataColumn ColEmail = ds.Tables[0].Columns["Email"];
//all emails are stored in a linst Mail
List<string> Mail = new List<string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
String MailData = row[ColEmail].ToString();
Mail.Add(MailData);
}
//Json serializer is used to convert the list data into jason format
//System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
// string a = JsonConvert.SerializeObject(Mail);
string ss = JsonConvert.SerializeObject(Mail, Formatting.Indented);
string d = ss.Substring(1, ss.Length - 1).ToString();
return ss;
//System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//return serializer.Serialize(Mail);
}
#endregion
directly in the source then the output is right i am getting this three words diffrently in autocomplete textbox suggestions plzz help thanx in advance

Pass Dictionary<String,List<String>> to Javascript array

This is my web service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Dictionary<string,List<string>> GetCategorias()
{
var diccionario = new Dictionary<string, List<string>>();
var categoria = "Recursos Humanos";
diccionario.Add(categoria,new List<string>());
diccionario[categoria].Add("Busqueda de recursos");
diccionario[categoria].Add("Busqueda de recursos humanos");
var categoria1 = "Informatica";
diccionario.Add(categoria1, new List<string>());
diccionario[categoria1].Add("IT");
diccionario[categoria1].Add("Departamento de Insfractructura");
//var serializer = new JavaScriptSerializer();
//string json = serializer.Serialize((object)diccionario);
return diccionario;
}
I received the dictionary in Javascript as:
function get_Categorias_Comunidades() {
$.ajax({
type: "POST",
url: "Lista_Categoria_comunidad.asmx/GetCategorias",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: llamada_Webservice,
error: llamada_Error
});
}
function llamada_Webservice(peticion) {
debugger;
}
How do I parse the keys and values to an array?
Something like this
function llamada_Webservice(peticion) {
var categories = peticion;
for(item in categories{ // Data is saved in the variable named d if it's ASP.NET WebService
var categoria = item; // The name
var list = categories[item]; // The array that you could loop thru
}
}

MVC JsonResult Method not accepting parameter

I have an MVC JsonResult Method that accepts one string parameter:
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
With a jquery method calling the method:
//Fetch Destinations
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "{countryId:'" + countryId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
BindDestinationSelect(msg)
}
});
});
However, the JsonResult seems to only receive a null parameter. Even though Firebug is showing that a parameter is being passed:
JSON
countryId
"11"
Source
{countryId:'11'}
Any ideas? Thanks
I think the problem is in how you are actually passing the data, you are doing so as a string:
data: "{countryId:'" + countryId + "'}",
When in reality, you should be using a structure on the client side;
data: { countryId: countryId },
jQuery should be able to handle passing the id correctly then. As you are doing it now, it is trying to send JSON to the server, which is not what MVC is expecting, it's expecting a POST with name/value pairs.
You might also want to consider the jQuery Form Plugin, as it makes serializing your Javascript structures into POST data very easy.
Ah, after much searching I've discovered the reason why it fails.
Nothing to do with malformed JSON etc, but rather the fact that the controller method doesnt know what to expect if you try to pass it JSON values:
http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863
So in my case, I've just elected to pass it a single string value.
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "countryId=" + countryId,
success: function (msg) {
BindDestinationSelect(msg.Data)
}
});
Here I suggest you to decorate your action with HttpPost attribute
Like :-
[HttpPost]
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
public JsonResult BindAllData(string Userid)
{
List<VoteList> list = new List<VoteList>();
var indexlist = db.TB_WebSites.ToList();
int i = 0;
var countlist = db.Tb_Votes.ToList();
var VCountList = db.Tb_Votes.ToList();
foreach (TB_WebSites vt in indexlist)
{
bool voted = false;
}
return Json(new { List = _list });
}
function DataBind() {
$("#LoadingDatas").show();
var userid = $("#FBUserId").text();
//alert('Data : ' + userid);
var InnerHtml = "";
$.ajax(
{
url: '/Gitex/BindAllData/',
type: 'POST',
data: { "Userid": userid },
dataType: 'json',
async: true,
success: function (data) {
//alert('Done');
//alert(data.List.length);
for (var i = 0; i < data.List.length; i++) {
});
}
Try this, it worked for me
jQuery function
success :function(Destinations)

Categories