I have a problem with converting datasource to json_data. Here is my code:
In my default.aspx.cs:
[WebMethod]
public string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
And here is in my default.apsx page:
var data2 = { };
function GetJsonData(callback) {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetJson",
//contentType: "application/json; charset=utf-8",
//data: '{name:""}',
dataType: "json",
cache: false,
success: function(msg) {
callback(msg);
},
error: function(err) {
alert('error');
}
});
}
data2 = GetJsonData();
$(function() {
$("#MainTree,#SubTree").jstree({
"json_data": {
"data": data2,
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
When I hide "data", ofcourse it won't create node. But now I want to call method GetJson from default.aspx.cs to get json_data from datasource. It always show "..Loading".. I'm using jsTree and just .net framework 2.0..Please help me to find out the solution for this..Thanks
Use Default.aspx/GetJson instead of Default.aspx.cs/GetJson.
In addition to changing the filename(as #Alex Filipovici mentioned), your method needs to be static.
[WebMethod]
public static string GetJson()
{
}
EDIT:::
This is what I did and got results back:
$(document).ready(function () {
$("[id$=_btnPostReminder]").click(function () {
var a = "";
var remindertext = "";
var re = "";
var res = "";
$.ajax({
type: "POST",
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function Ret(response) {
var Result = response.d
alert(Result)
return false;
},
error: function (data, status, jqXHR) {
alert(jqXHR);
}
});
return false;
});
});
Related
I tried to binding remote DataSource for my Kendo DropDownList, but the Kendo Datasource could parse the json response correctly. The result turns out to be "undefined" and recognize every single charachter in the data as a selection. I have no idea where the bug is, please help me!
Responce from controllor:
"[{"CODE_ID":"A","CODE_NAME":"Free"},{"CODE_ID":"B","CODE_NAME":"Borrowed"},{"CODE_ID":"U","CODE_NAME":"Unable"},{"CODE_ID":"C","CODE_NAME":"To be Borrowed"}]"
HTML Result
Front-end js code for Kendo DropDownList
$(document).ready(function () {
$("#search_category").kendoDropDownList({
dataTextField: "CODE_NAME",
dataValueField: "CODE_ID",
dataSource: {
transport: {
read: {
type: "GET",
url: "/BookData/GetDataList",
data: { name: "category" },
dataType: "json"
}
},
},
});
}
BookDataControllor
[HttpGet()]
public JsonResult GetDatalist(string name)
{
string result;
try
{
switch (name)
{
case "category":
result = codeService.GetDataList("CODE_ID, CODE_NAME",
"BOOK_CODE", "CODE_TYPE = 'BOOK_STATUS'");
break;
default:
return Json(false);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false);
}
}
back-end class CodeService
private DataTable GetDataTable(string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(this.GetDBConnectionString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
sqlAdapter.Fill(dt);
conn.Close();
}
return dt;
}
public string GetDataList(string col, string src, string cond)
{
DataTable dt = GetDataTable(string.Format(#"SELECT {0} FROM {1} WHERE {2}",
col, src, cond).ToUpper());
string result = JsonConvert.SerializeObject(dt);
return result;
}
You are returning CODE_ID and CODE_NAME in your controller, but the values you're referencing on the front-end are Category_Name and Category_ID. Change them to reference the correct column names:
$('#search_category').kendoDropDownList({
dataTextField: 'CODE_NAME',
dataValueField: 'CODE_ID',
dataSource: {
transport: {
read: {
type: 'GET',
url: '/BookData/GetDataList',
data: { name: 'category' },
dataType: 'json',
success: function (response) {
console.log(response);
}
}
}
}
});
It seems that even returning your data with Json(result) as JsonResult, the response content could be a string, which the DataSource is not handling the right way.
Try enrusing that it will be json with parse method:
$(document).ready(function () {
$("#search_category").kendoDropDownList({
dataTextField: "CODE_NAME",
dataValueField: "CODE_ID",
dataSource: {
transport: {
read: {
type: "GET",
url: "/BookData/GetDataList",
data: { name: "category" },
dataType: "json"
}
},
schema: {
parse: function(data) {
// Here you can check what 'data' really is
console.log(data);
return JSON.parse(data);
}
}
},
});
}
Ok I have created a tab with a table inside of it as follows -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST", url: "../WebMethods/MarketPersuitMethods.aspx/GetColumnHeaders",
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$tbody.append("<th>" + value.ColumnsName + "</th>");
});
$tbody.append('<tr />').children('tr:last')
setTimeout(function () {
}, 1000);
}
});
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
//$table.appendTo('#TabbedMktList');
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
Here is my C# Code
[WebMethod(EnableSession = true)]
public static string GetQueryInfo()
{
String daresult = null;
DataTable yourDatable = new DataTable();
string strConnString = WebConfigurationManager.ConnectionStrings["TimeClock"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = "select * from OCI_TEXT_PROJECT_MASTER where proj_id=2049";
da.SelectCommand = cmd;
cmd.CommandTimeout = 30;
cmd.Connection = con;
con.Open();
da.Fill(yourDatable);
daresult = DataSetToJSON(yourDatable);
return daresult;
}
public static string DataSetToJSON(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table);
return JSONString;
}
It is creating the column headers as I wish for it to do. However, I need to populate all the JSON data for the rows below it. I would not know the column headers as they can change.
I am able to see my results are coming back in JSON data -
[{"Project ID":"18180","OPRN":null,"Proj_Type":"2049","Client Name":null,"client_id":null,"ClientContact":null,"Contact_ID":null,"PN":null,"CompleteDate":"2020-05-21T00:00:00","cost":null,"SQFT":2000,"BIM":null,"LEED":"NO ","Delivery_Meth":"Corey ","City":"Orlando","State":"FL ","County":"Orange","IT":"1141","Project Name":null,"Address":"1234. Orlando Ave","zip":"12345","notes":"<p class=\"MsoNormal\"><b>EXTRA TESTING 1-2-3-43</b></p>","PM":"1141","OLDOWNER":null,"Owner_Contact":null,"ProjectManager":"Corey ","Architect":"Collier Health Services","ContractorORG":"BVW Development","ArchitectID":929,"PNAME":"OCI DYNAMICS CRM PROJECT MANAGEMENT SOFTWARE","PROJ_ID":2049,"Office":"Maitland","MPROJECT":null,"Contractor":930,"addr2":"","PROJSTATUS":2,"TotalProjectTime":null,"corp":"0","ProjectStatus":"Construction","TotalDesignTime":null,"OFFNUM":1,"Owner":null,"ProjectType":null,"MarketSector":"FINANCIAL","users":"1141","team":null,"BuildingType":null,"ETA":null,"designstartdate":null,"FINALCONTRUCT":24000.0000,"ESTCONSTRUCT":15000.0000,"Units":"12","WebType":"P","RequestedBy":null,"RequestedDate":null,"Status":"Interview","RFPDATE":null,"SENTDATE":null,"InterviewDate":null,"OCIDATE":null,"Method":null,"ContractType":"0","ContractName":null,"Tags":"CRM FINANCIAL NewTest rigtest2","TotalProfit/Loss":3,"Disciplines":"Mechanical, CAD, Clerical, QA/QC, Project Management","ChillerType":"1","Revit":"2017","Tons":145,"Rooms":5}]
However -
I have no idea where to get it to map over automatically.
I would ideally think somehow to map it based on the TH header text because they would be the same.
My issue is somewhere in here
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
Figured it out -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (d) {
var data = $.parseJSON(d.d);
var colHeader = Object.keys(data[0]);
for (var i = 0; i < colHeader.length; i++) {
$tbody.append("<th>" + colHeader[i] + "</th>");
}
//sets new line
$tbody.append('<tr />').children('tr:last')
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < colHeader.length; j++) {
$tbody.append('<td>' + data[i][colHeader[j]] + '</td>');
}
$tbody.append('<tr />').children('tr:last')
}
setTimeout(function () {
}, 1000);
}
});
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}
When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}
I get data from Webmethod & it need to bind to a table.But my Jquery function not success.Not call webmethod because of Ajax call error.
My Webmethod is
[WebMethod, ScriptMethod]
public static List<UploadedFiles> GetAllUploadedFiles()
{
List<UploadedFiles> UploadedFilesDetails = new List<UploadedFiles>();
try
{
SqlCommand comGetAllFiles = new SqlCommand("SP_GetAllUploadedFiles", conDB);
comGetAllFiles.CommandType = CommandType.StoredProcedure;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comGetAllFiles.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
UploadedFilesDetails.Add(new UploadedFiles
{
Id = (int)r["Id"],
UserId =(Guid)r["UserId"],
FilePath = r["FilePath"].ToString(),
Date =(DateTime) r["Date"]
});
}
}
catch(Exception ee)
{
}
finally
{
conDB.Close();
}
return UploadedFilesDetails;
My Ajax Function
<script>
$(function () {
LoadUploadFiles();
});
function LoadUploadFiles() {
var url = '<%=ResolveUrl("WebMethods.aspx/GetAllUploadedFiles") %>';
$.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
alert("x");//<-- This alert firing
$.each(Result.d, function (key, value) {
alert(Result.d); //<-- Thisone not firing
$("#uploaddata").append($("<table><tr></tr></table>").val
(value.Id).html(value.FilePath));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
</script>
here is my code:
var data = "";
$(function() {
$("#MainTree,#SubTree").jstree({
"json_data": {
"data": data,
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
//data: '{name:""}',
dataType: "json",
cache: false,
success: function(msg) {
data = msg;
},
error: function(err) {
alert(err);
}
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
This is my GetJson method:
[System.Web.Services.WebMethod]
public static string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
In my Default.aspx.cs, I created a method name GetJson, when I run this code, it returned alert(error). Please help me to find out what was happened?
Editted: when i check in browser,the method get status code 200 OK, but in respone..it show me the page Default.aspx(context html)