Fancytree not loading with ajax request - c#

I'm having a problem with fancytree.
I have an aspx page, with a webmethod on the codebehind.
I was trying to initialize the tree with an ajax call, but for some reason it looks the ajax call isn't getting there.
This is my javascript code to initialize the tree:
<script type="text/javascript">
$(function () {
var DT = $.ui.fancytree;
var tree = "";
$.ui.fancytree.debug("Using fancytree " + $.ui.fancytree.version);
/* Load tree from Ajax JSON
*/
$("#tree2").fancytree({
source: {
url: "tree.aspx/getTreeData"
}
});
});
</script>
and this is my codebehind webmethod:
namespace TreeGen
{
public partial class tree : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static List<Curso> getTreeData()
{
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
CourseSerializer course = new CourseSerializer();
course.children = new List<Curso>()
{
new Curso(){
key = "1",
title = "aaaa",
}
};
List<CourseSerializer> courses = new List<CourseSerializer>() { course };
string TheJson = TheSerializer.Serialize(course.children);
Console.WriteLine(TheJson);
return course.children;
}
}
}
What am i doing wrong?
I tried to make a ajax request to the webmethod and i am able to retrieve the json string.
But when i use the fancytree i can't populate the tree!
Thanks in advance!
Regards!

For anyone interested...
The ajax requests made by fancytree are all "GET" requests by default.
I added the ajax options as shown below, and the issue is now solved.
$('#tree2').fancytree({
ajax: { type: "POST", contentType: "application/json" },
source: {
url: "/tree.aspx/getTreeData"
}
});
Regards!

Related

How to call api from ASP.NET razor view

Just as stated above, I am not sure how to call an API.
I have done it using fetch in the example below:
fetch("https://localhost:5001/api/patients/add", {
method: "POST",
mode: "cors",
cache: "no-cache",
headers: { "Content-Type": "application/json" },
body: postBody
});}
But it seems there is a different way of doing things in Razor view.
Below is what I have in my API:
// GET: api/Patients/5
[HttpGet("{id}")]
public async Task<ActionResult<Patient>> GetPatient(int id)
{
var patient = await _context.Patient.FindAsync(id);
if (patient == null)
{
return NotFound();
}
return patient;
}
It's just the GET made when creating an API in Visual Studio.
The following ajax call, within a script tag inside the razor page - although this is not best practice - would work as follows:
$.ajax({
type: "GET",
url: "#Url.Action("GetPatient", "Patients")",
data: { id : 1234 },
success: function(result){
//do something with result here
alert(result);
}
});
The second parameter of Url.Action is the Controller Name. This may need to be adapted for yourself.
This is what I ended up doing that worked. Thanks for the help guys!
$(document).ready(function () {
var options = {};
options.url = "https://localhost:44381/api/States";
options.type = "GET";
options.dataType = "json";
options.success = function (states) {
states.forEach(function (state) {
$("#state").append("<option>" + state.stateName + "</option>"
)
});
};
options.error = function () {
$("#msg").html("Error while calling the Web API!");
};
$.ajax(options);
});

How can I return list object to ajax call back function from asp.net web form?

I'm beginner in asp.net and write simple web application to show user any chart using highcharts tools, in highcharts need read data with ajax and for that purpose I write this code:
function FetchData() {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "CS.aspx/GetDataBehzad",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
alert(aData);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
}
and in CS.aspx write this code:
[System.Web.Services.WebMethod]
public List<int> GetDataBehzad()
{
List<int> list = new List<int>();
list.Add(10);
list.Add(100);
return list;
}
But when I run the application I get OnErrorCall function alert from ajax, how can I solve that? What is problem? thanks every one.
Make your Method "Static"
that is the only issue in your code
see below
[System.Web.Services.WebMethod]
public static List<int> GetDataBehzad()
{
List<int> list = new List<int>();
list.Add(10);
list.Add(100);
return list;
}
Let see this is not and complete answer but a direction to a result. Try something like returning Json/Xml result from the action WebMethod. I have tried with mvc it is working on my site. You just need to see if JsonResult/Similar something is by default supported in webform or just find a class library.
public JsonResult GetDataBehzad()
{
List<int> list = new List<int>();
list.Add(10);
list.Add(100);
return Json(list, JsonRequestBehavior.AllowGet);
}
Use [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute.
Your method:
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<int> GetDataBehzad()
{
List<int> list = new List<int>();
list.Add(10);
list.Add(100);
return list;
}

Jquery JSON and C# : Reading JSON reply from C# HttpHandler

I am having some trouble figuring out to read the JSON returned from my HttpHandler.
The data being returned is this (according to Firebug):
[{"ID":2,"Name":"Fred Johnson","PhoneNumber":"444-444-4444","Notes":"Note Data","Representative":1,"StreetNumber":76547,"StreetName":"Juniper St.","City":"Burbank"}]
HttpHandler Code
public class RequestHandler : IHttpHandler
{
public RequestHandler()
{ }
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
var thisID = Convert.ToInt32(context.Request["Id"]);
List<WW.Data.Customer> thisCustomer = WW.Business.Customer.getCustomerByID(thisID);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string lookedUpCustomer = javaScriptSerializer.Serialize(thisCustomer);
context.Response.ContentType = "text/html";
context.Response.Write(lookedUpCustomer);
}
}
JQUERY CODE
<script type="text/javascript">
function sendData() {
alert("start");
var thisID = $("#Text1").val()
var arr = { ID: thisID};
$.ajax(
{
url: "jsonpost.ww",
type: "POST",
data: arr,
dataType: 'json',
async: true,
success: function (data) {
$("#Text2").val = data.Name;
$("#Text3").val = data.StreetNumber;
$("#Text4").val = data.StreetName;
$("#Text5").val = data.City;
$("#Text6").val = data.PhoneNumber;
}
}
);
alert("end");
}
</script>
So basically, I am having trouble reading that JSON string data when it is returned on success. Anyone see anything that would cause this?
Any help is appreciated.
Thanks,
CSS
The json response which you are getting should be in ():
$("#Text2").val(data.Name);
$("#Text3").val(data.StreetNumber);
$("#Text4").val(data.StreetName);
$("#Text5").val(data.City);
$("#Text6").val(data.PhoneNumber);
This is the correct way of assigning values to inputs.
Your JSON is formatted such that the object you need is the first element of an array. So in your success callback, instead of doing data.name, you need to do data[0].name.

fullCalendar events not showing even though correct JSON feed

As a bunch of others I have a problem getting my JSON feed events to render in the calendar. The problem is often wrong JSON formating, but this is not the case since I've validated it with JSONlint and hardcoded the JSON feed in Site.Master with positive result.
FireBug is getting the JSON response correctly but it is still not showing up in fullCalendar. I'm out of ideas.
The FireBug response:
[{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}]
JSON.aspx
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get events from db and add to list.
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
Response.Write(json);
Response.End();
}
}
Site.master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' />
<script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script>
<script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: 'JSON.aspx'
})
});
</script>
I've been scanning related questions for days but none of them seems to fix mine...
Try this , you have to have a webmethod in aspx file that fullcalendar can call asynchronously
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: function (start, end, callback) {
$.ajax({
type: "POST", //WebMethods will not allow GET
url: "json.aspx/GetEvents", //url of a webmethod - example below
data: "{'userID':'" + $('#<%= hidUserID.ClientID %>').val() + "'}", //this is what I use to pass who's calendar it is
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d"
$(obj.event).each(function () { //yours is obj.calevent
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
callback(events);
}
});
}
})
then this would be in json.aspx
[WebMethod(EnableSession = true)]
public static string GetEvents(string userID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
return json;
}

Why is this jQuery ajax call to C# web method not working

Here is my JS:
function declassifyAjax(e) {
var items = getSelected();
var docIds = new Array();
items.each(get);
//get ids of QcItem/docId we are dealing with
function get(count, el) {
docIds[count] = $(el).parent().attr('id');
}
var dataObj = new Object();
dataObj.batchId = batchId;
dataObj.docIds = docIds;
var dataString = JSON.stringify(dataObj)
//make call to webservice to get html to recreate view showing
//pending declassification
$.ajax({
type: "POST",
url: applicationRoot + 'Models/BatchQC.asmx/declassify',
data: dataString,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (ProcessWebMethodResult.processWebMethodResult(data) == true) {
declassifyProcess(data, e);
}
},
error: function (e) {
alert("Failed to Get declassification details");
}
});
}
And here is my Web Service:
//type to represent the input the declassify method
public class DeclassifyType
{
public int batchId;
public string[] docIds;
}
[WebMethod(EnableSession = true)]
public WebMethodResult declassify(DeclassifyType dataString)
{
}
Any and all help appreciated!
Debugging in Firebug shows that the variables dataObj, batchId, docIds and dataString are correct. There is something wrong with the way my Web Method signature is setup I think, because the Ajax is never fired off. When stepping through the .ajax method, it goes to error, not success.
Your web methods expects one parameter, the data object you already have, but you're passing multiple parameters since you're passing the object directly.
Instead, you need to have an object with one property, dataString, and that property's value should be your object, like this:
var dataString = JSON.stringify({ dataString: dataObj });
▲--should match--▼
public WebMethodResult declassify(DeclassifyType dataString)
Ah, I just fixed it,
just changed the signature to
[WebMethod(EnableSession = true)]
public WebMethodResult declassify(int batchId, string[] docIds)
{
}
Simple really. Thanks for checking my post!

Categories