Here is my code in Default.aspx:
$(function() {
var dataSource = {};
$("#MainTree,#SubTree").jstree({
"json_data": {
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
},
data: dataSource,
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
And here is GetJson method in Default.aspx.cs:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[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);
}
EDIT:
This is the result when i check GetJson method respone:
{"d":"[{\"EmpId\":25,\"Name\":\"Rk\",\"Address\":\"Gurgaon\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":50,\"Name\":\"Sachin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":10,\"Name\":\"Nitin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":21,\"Name\":\"Aditya\",\"Address\":\"Meerut\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":100,\"Name\":\"Mohan\",\"Address\":\"Banglore\",\"Date\":\"\/Date(1372999726975)\/\"}]"}
And the result is nothing..It just appeared "..Loading" flashly and then it return blank page..please help me to show what's the problem here is..Thanks a lot.
It seems that you've not read the documentation properly so I would suggest you do that first.
When you use json_data plugin, you need to follow basic structure as shown below and could be found here, that means you need to provide Json data in below format:
{
"data" : "node_title",
// omit `attr` if not needed; the `attr` object gets passed to the jQuery `attr` function
"attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" },
// `state` and `children` are only used for NON-leaf nodes
"state" : "closed", // or "open", defaults to "closed"
"children" : [ /* an array of child nodes objects */ ]
}
Taking response structure into consideration, you need to have server side class as shown below:
public class Emp
{
public EmpAttribute attr { get; set; }
public string data { get; set; }
}
public class EmpAttribute
{
public string id;
public bool selected;
}
And your pagemethod should look alike below:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static List<Emp> GetJson()
{
List<Emp> empTreeArray = new List<Emp>();
Emp emp1 = new Emp()
{
attr = new EmpAttribute(){ id= "25",selected=false},
data = "Nitin-Gurgaon"
};
Emp emp2 = new Emp()
{
attr = new EmpAttribute(){ id="50",selected=false},
data = "Sachin-Noida"
};
empTreeArray.Add(emp1);
empTreeArray.Add(emp2);
return empTreeArray;
}
Your clientside binding code should be like below:
$(function() {
var dataSource = {};
$("#demo1").jstree({
"json_data": {
"ajax":{
"type": "POST",
"url": "Default2.aspx/GetJson",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
success: function(msg) {
return msg.d;
},
error: function(err) {
alert(err);
}
}
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
Notice return msg.d in Success function that is missing from your code.
More examples could be found here
Please go through documentation of any plugin you use next time.
type http://Default.aspx/GetJson directly in browser and check whether correct data is coming or not.
Other two locations where you can add debugging code is
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
}
add breakpoints and debug the javascript.
The response is encapsulated in a property called "d". Instead of datasource = msg you should have datasource = msg.d
Related
I want to send this Array with Ajax to api :
var receipt = Array();
receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];
And this is my Ajax body :
var r = JSON.stringify(receipt);
$.ajax({
type: "POST",
dataType: "Json",
contentType: "application/json; charset=utf-8",
data: r,
url: "api/Receipt",
success: function (result) {
// To Do
console.info(result);
},
error: function (result) {
console.info(result);
}
});
And this is what i get as Json :
{[
{
"Service": "Saab",
"Order": "20"
},
{
"Service": "Volvo",
"Order": "12"
},
{
"Service": "BMW",
"Order": "25"
}
]}
And i catch them in api side Like this :
[Route("api/Receipt")]
[WebMethod]
public string Receipt_Turn(object obj)
{
dynamic dyn = JsonConvert.DeserializeObject(obj.ToString());
if (dyn != null)
{
return dyn[1].ToString();
}
else
{
return "false";
}
}
And it works, the part return dyn[1].ToString() returns second record of my Array. But i want to convert this dynamic variable to a list or array of a model .
Here is my model :
[Serializable()]
public class Receipt
{
public string Service { get; set; }
public string Order { get; set; }
}
I want to act with it like this :
string serv = receipt[1].Service;
How can i do it ?
Thanks...
Delete the Array Part in Your JS Script and Write it Like this :
var receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];
in this shape you are sending an Object. in your code i guess you are sending an JArray So it Will make some Problems in Converting from JArray to another Type .
in your API Side , Edit Your Code As Below :
public string Receipt_Turn(object r)
{
//important Line Here
List<Receipt> rr = JsonConvert.DeserializeObject<List<Receipt>>(r.ToString());
if (rr != null)
{
return rr[1].ToString();
}
else
{
return "false";
}
}
as you can see, we get it Like an Object and then we will be able to Get Ready your DeserializeObject part Like i mentioned.
you most declare a List of your Model, and after part DeserializeObject add that Type You want to Convert it to.
here Cause we Declared List<Receipt> , we should convert our DeserializeObject to it, so we add <List<Receipt>> after DeserializeObject.
and Finally you can use it Like You wish .
string serv = rr[1].Service;
Assuming you are using .NET Core, it should be able to bind it automatically if you do something like this:
```
[Route("api/Receipt")]
[WebMethod]
public string Receipt_Turn(List<Receipt> receipts)
{
if (receipts != null)
{
return "seomthing";
}
else
{
return "false";
}
}
```
I am trying to post List of object (or array of object) to c# Webmethod. I am understanding how to receive as parameter in the method and convert into local List of object?.
for (var i = 0; i < usersInfo.length; i++) {
user = {
UserName : usersInfo[i].UserName,
Email : usersInfo[i].Email,
Status : status
};
users.push(user);
}
var results = "";
$('#lblError').val('');
if (users.length > 0) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'UserValidation.aspx/ShowResults',
data: "{'UsersInfo':'" + JSON.stringify(users) + "'}",
async: false,
success: function (data) {
results = data.d;
$('#lblError').val(results);
},
error: function (xhr, status, error) {
var exception = JSON.parse(xhr.responseText);
alert(exception.Message);
}
});
}
Code behind
[WebMethod]
public static void ShowResults(//Here how receive list object from javascript)
{
//convert parameter to List<UsersInfo>
}
public partial class UsersInfo
{
public string UserName { get; set; }
public string Email { get; set; }
public string Status { get; set; }
}
Try to replace this line
data: JSON.stringify({ UsersInfo: users}),
James you are the right track; you need to define the correct type for the ShowResults parameter so that the binding will work and bind the incoming json to your UsersInfo class.
Your UsersInfo class appears to be a simple POCO so should bind without any custom binding logic :
[WebMethod]
public static void ShowResults(List<UsersInfo> UsersInfo)
{
//No need to convert
}
I've been using a hard coded JSON object:
var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
I'm then iterating this object calling the items by index and using .length:
for (var i = 0; i < resuts.length; i++) {
console.log('id:' + resuts[i].id + ' | ' + 'Code:' + resuts[i].Code}
Now I want to pull this data from the server so I created an object to handle the properties and have this action method:
public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
{
results = new List<Question>()
{
new Question { id = 1, Code = "Code A},
new Question { id = 1, Code = "Code B}
}
});
return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}
I'm calling it with this AJAX:
function GetResultsJSON() {
$.ajax({
type: 'GET',
url: '/Home/GetResults/',
dataType: 'json',
traditional: true,
success: function (data) {
results = data;
},
error: function (data) {
alert('Error.');
}
})
};
Now my results object contains:
"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
Now I get JavaScript errors when trying to use the length property or call items by index. From what I have read up on, I think my original hard coded object is just an array, however, I have to work differently with the JSON that's returned from my controller.
Can anyone advise on either returning the array format that I was originally working with or the best way to handle the JSON format as it's returned here? I have tried things like
$.each(data, function(i, obj) {
alert(obj.name);
});
but this returns undefined. Any help would be great.
public JsonResult TestAjax(int leagueId)
{
var results = new List<BaseballViewModel>()
{
new BaseballViewModel{ DivisionId = 1},
new BaseballViewModel{ DivisionId = 2}
}.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: "/Home/TestAjax",
type: "GET",
data: { leagueId: 5 },
success: function (data) {
// alert(JSON.stringify(data)); show entire object in JSON format
$.each(data, function (i, obj) {
alert(obj.DivisionId);
});
}
});
Instead of:
$.each(data, function(i, obj) {
alert(obj.name);
});
why don't you try:
$.each(data.results, function(i, obj) {
alert(obj.name);
});
If you create a Model class that way :
[Serializable()]
public class MyResponse
{
public int Id {get; set;}
public string Code {get; set;}
}
And that you create a list of "MyResponse"
You will just have to do
return Json(new { data = listOfMyResponse}, JsonRequestBehavior.AllowGet);
I am using jstree plugin, and I need json format that is inside object.
this is my output:
[{"id":"1","text":"Document Management","parent":"#","icon":"fa fa-table","selected":1}
,{"id":"2","text":"Document List","parent":"1","icon":"fa fa-list","selected":1}
,{"id":"7","text":"Hazard","parent":"#","icon":"fa fa-file-text","selected":1}]
this is what I need:
[{"id":"1","text":"Document Management","parent":"#","icon":"fa fa-table",state: { opened: true, selected: true }}}
,{"id":"2","text":"Document List","parent":"1","icon":"fa fa-list",state: { opened: true, selected: true }}}
,{"id":"7","text":"Hazard","parent":"#","icon":"fa fa-file-text",state: { opened: true, selected: true }}}]
and these are my c# and js codes which creates json serialising and treeview;
c#
[WebMethod]
public static string Menu()
{
ClassSystemAccessPolicy classDocumentPolicy = new ClassSystemAccessPolicy();
DataTable dt = new DataTable();
dt = classDocumentPolicy.Permission_Load().Tables[0];
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;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
js
var MenuTree = function () {
$.ajax({
type: "POST",
url: "Permission.aspx/Menu",
contentType: "application/json",
dataType: "json",
success: function (data) {
var menu$json = JSON.parse(data.d);
$('#tree_menu').jstree({
'plugins': ["wholerow", "checkbox", "types"],
'core': {
"themes": {
"responsive": false
},
'data': menu$json
}
});
console.log(menu$json)
},
error: function () {
console.log('err')
}
});
How can I serialise like state: { selected: true } ?
You need to create your own DTO(Data Transfer Object) for this
public class JSTreeDTO
{
public string id{get;set;}
public string text{get;set;}
public string text{get;set;}
public string parent {get;set;}
public string icon{get;set;}
public StateDTO state{get;set;}
}
public class StateDTO
{
public bool opened{get;set;}
public bool selected{get;set;}
}
Then create it inside loop
List<JSTreeDTO> treeList=new List<JSTreeDTO>();
foreach (DataRow dr in dt.Rows)
{
JSTreeDTO node=new JSTreeDTO();
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
node.id=dr["id"];//etc
node.state=new StateDTO();
node.state.opened=true;//based on your logic
}
treeList.Add(node);
return serializer.Serialize(treeList);
}
Can i use session values inside a WebMethod?
I've tried using System.Web.Services.WebMethod(EnableSession = true) but i can't access Session parameter like in this example:
[System.Web.Services.WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod()]
public static String checaItem(String id)
{
return "zeta";
}
here's the JS who calls the webmethod:
$.ajax({
type: "POST",
url: 'Catalogo.aspx/checaItem',
data: "{ id : 'teste' }",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
You can use:
HttpContext.Current.Session
But it will be null unless you also specify EnableSession=true:
[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{
return "zeta";
}
There are two ways to enable session for a Web Method:
1. [WebMethod(enableSession:true)]
2. [WebMethod(EnableSession = true)]
The first one with constructor argument enableSession:true doesn't work for me. The second one with EnableSession property works.
For enable session we have to use [WebMethod(enableSession:true)]
[WebMethod(EnableSession=true)]
public string saveName(string name)
{
List<string> li;
if (Session["Name"] == null)
{
Session["Name"] = name;
return "Data saved successfully.";
}
else
{
Session["Name"] = Session["Name"] + "," + name;
return "Data saved successfully.";
}
}
Now to retrive these names using session we can go like this
[WebMethod(EnableSession = true)]
public List<string> Display()
{
List<string> li1 = new List<string>();
if (Session["Name"] == null)
{
li1.Add("No record to display");
return li1;
}
else
{
string[] names = Session["Name"].ToString().Split(',');
foreach(string s in names)
{
li1.Add(s);
}
return li1;
}
}
so it will retrive all the names from the session and show.
You can try like this
[WebMethod]
public static void MyMethod(string ProductID, string Price, string Quantity, string Total)// Add new parameter Here
{
db_class Connstring = new db_class();
try
{
DataTable dt = (DataTable)HttpContext.Current.Session["aaa"];
if (dt == null)
{
DataTable dtable = new DataTable();
dtable.Clear();
dtable.Columns.Add("ProductID");// Add new parameter Here
dtable.Columns.Add("Price");
dtable.Columns.Add("Quantity");
dtable.Columns.Add("Total");
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dtable.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dtable;
}
else
{
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dt.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dt;
}
}
catch (Exception)
{
throw;
}
}
Take a look at you web.config if session is enabled. This post here might give more ideas.
https://stackoverflow.com/a/15711748/314373
In C#, on code behind page using web method,
[WebMethod(EnableSession = true)]
public static int checkActiveSession()
{
if (HttpContext.Current.Session["USERID"] == null)
{
return 0;
}
else
{
return 1;
}
}
And, in aspx page,
$.ajax({
type: "post",
url: "", // url here
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{ }',
crossDomain: true,
async: false,
success: function (data) {
returnValue = data.d;
if (returnValue == 1) {
}
else {
alert("Your session has expired");
window.location = "../Default.aspx";
}
},
error: function (request, status, error) {
returnValue = 0;
}
});