Why i get error when i call this collection? All i need to to bind this collection to my Gridview control.....
C# Code:
[WebMethod]
public static List<Customer> GetAllCustomers()
{
using (masterEntities context = new masterEntities())
{
return context.Customer.ToList();
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("id");
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Rows.Add();
GridView1.DataSource = table;
GridView1.DataBind();
}
Ajax code:
function GetCustomers() {
$.ajax({
type: "POST",
url: "12.aspx/GetAllCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (data) {
alert(data.d);
}
});
function OnSuccess(data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].Id + "</td><td>" + data.d[i].Name + "</td><td>" + data.d[i].Age + "</td></tr>");
}
}
This is what i get when i call that collection
http://s22.postimg.org/6qv6tr8g1/aaaaaaaaaaaaaaaaa.jpg
The problem is with the $.ajax error handler:
error: function (data) {
alert(data.d);
}
Error hanlder written like this, gives you very little information on what happened with the failed request. A better way to write your error handler would be like this:
error: function (jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(jqXHR.responseText);
}
With error handler written this way you can look e.g. Chrome Developer Tools's console window and see the value of jqXHR.responseText which contains detailed error description of what went wrong.
Although be careful to replace console.log statements with more meaningful error messages when you deploy your web applications.
Here's a link to jQuery API documentation (look for error handler description): http://api.jquery.com/jQuery.ajax/
Hope this helps!
Regards,
Uros
Related
I'm getting the error
**POST http://localhost:34169/createNew.aspx.cs/Confirm 403 (Forbidden) **
when I am trying to call a CodeBehind function with Jquery AJAX.
My code:
function CallConfirmMethod(str) {
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "createNew.aspx.cs/Confirm",
data: "{'smallPos': " + str + "}",
success: function (result) { alert("successful!"); }
});
}
And the CodeBehind function (doesnt actually do anything, just to test things out):
[System.Web.Services.WebMethod(BufferResponse = false)]
protected void Confirm(string str) {
// SKICKA SQL-QUERY
Response.Write("Funktionen kallas! " + str);
}
I think your mistake is in url createNew.aspx.cs/Confirm you should change it to createNew.aspx/Confirm. Also it's good article Calling ASP.Net WebMethod using jQuery AJAX
Maybe you get 500, because you haven't close Response
[System.Web.Services.WebMethod(BufferResponse = false)]
protected void Confirm(string str) {
// SKICKA SQL-QUERY
Response.Clear();
Response.ContentType = "application/text";
Response.StatusCode = 200;
Response.Write("Funktionen kallas! " + str);
Response.Flush();
Response.End();
}
if you want send response in json this is article AJAX to web method not returning JSON
I have a very simple ajax call to my handler from jquery which is failing to retrive data and it gives me parsererror when i try to show the result in alert box.
ASP.NET Handler code:
public void ProcessRequest (HttpContext context) {
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
Jquery
$('.submit').on("click",function(e) {
e.preventDefault();
var data1 = { "hi": "hello" };
alert(data1.hi);
$.ajax({
url: "/charity-challenge/CompetitionHelper.ashx",
data: data1,
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("response = " + data);
},
error: function (data, status) {
alert("FAILED:" + status);
}
});
});
Note: I can see the response coming fine in chrome while debugging. BUT somehow when i try to show it in alert box it gives me parsererror.
Also, I want to assign the json data in handler. i dont have any clue how to do that.
i have a sample calss like this in handler. how to loop through the json data and assign values to this variables so i can work on those.
public class userData
{
public string EmailAddress { get; set; }
public string EntryId { get; set; }
}
Found the work around to this.
i added a complete callback and now its showing the result in alertbox. i dont know why it is not working without it BUT if someone knows please post the answer.
here is the complete call back.
complete: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
It has to do with your request payload being sent by the ajax call as hi=hello
As a test, try this (requires Newtonsoft.Json nuget):
public void ProcessRequest(HttpContext context)
{
//string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.ContentType = "application/json";
context.Response.Write(JsonConvert.SerializeObject(new { hi = "hello" }));
}
So I guess you have to parse your input stream e generate the json correctly.
You could also fix this in the client side, by calling using JSON.stringify(data1) in your data parameter in the ajax call.
I have a asp .net web page and a button in it. I'm calling an ajax method in the button click event as follows
$("#btnTest").click(function () {
$.ajax({
type: 'POST',
url: 'test2.aspx',
success: function (data) {
alert( data);
},
error: function (data) {
alert("In error ");
}
});
});
In success part alert( data) Im getting the html code of the page test2.aspx (which one I have given in ajax url).
In test2.aspx.cs code is given as below
protected void Page_Load(object sender, EventArgs e)
{
jsonTest();
}
public List<string> jsonTest()
{
List<string> list = new List<string>();
list.Add("aa");
list.Add("bb");
list.Add("cc");
return list;
}
Why this data in 'list' is not coming as response data in ajax?
Try Response.Write() method for that purpose
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("data to be returned");
}
Or try to write static webmethods in aspx page. Those methods can be call from ajax
You cannot return data from aspx to ajax. try this
HttpContext.Current.Response.Write(list);
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.SuppressContent = true;
This will help to solve your problem.
You can't call a normal page method from jQuery.
You need to create a web-method to access that from jQuery.
Here is a good link regarding how to call a page method
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Use like this..
$("#btnTest").click(function () {
$.ajax({
type: 'POST',
url: 'test2.aspx',
success: function (data) {
alert( data.d[0]);
alert( data.d[1]);
alert( data.d[2]);
},
error: function (data) {
alert("In error ");
}
});
});
I want bind new data to my ListView. But I can't
In server side I have:
[WebMethod]
public static void ChangeConditions(string ConditionIs)
{
DataTable dt = new DataTable();
dt = GetNewData(ConditionIs);
//can't to do it, because my WebMethod is static.
//listView.DataSource = dt;
//listView.DataBind();
}
private static DataTable GetNewData(string conditions)
{
DataTable NewData = new DataTable();
//Get new data from DB and want to return DataTable with new data.
//...
return NewData;
}
In client side I have:
$('#btnSend').live('click', function () {
$.ajax({
type: "POST",
url: "default.aspx/ChangeConditions",
data: '{"ConditionIs":"' + condition + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}
}); });
How I can rebind data to ListView?
P.S. When I write this post, I researched my question. And found solution:
put UpdatePanel around my ListView;
put ScriptManager above UpdatePanel;
put this line inside success function in JS: __doPostBack('UpdatePanel1', '');
And when I send my data from client to server into [WebMethod], I can fill my static DataTable, and Bind it in Page_Load.
But I want to interesting, can I use some other solution? Or maybe in my solution can have some bugs?
I have a page with this method in CreateTicket.aspx.cs:
[WebMethod()]
public static string Categories()
{
var business = new CategoryBusiness();
var categories = business.ListRootCategories();
return categories.Json();
}
And the javascript/jquery code on the page (same page, .aspx):
function LoadRootCategories() {
PageMethod("CreateTicket.aspx", "Categories", [], LoadCategoriesSucceded, LoadCategoriesFailed);
}
function PageMethod(page, fn, paramArray, successFn, errorFn)
{
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0)
{
for (var i=0; i<paramArray.length; i+=2)
{
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i+1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
Running it on firebug, I get the following error on console:
500 Internal Server Error
Unknown web method Categories.
[ArgumentException: Unknown web method Categories.
Parameter name: methodName]
System.Web.Script.Services.WebServiceData.GetMethodData(String methodName) +517489
System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs eventArgs) +168
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Why is this happening?
I resolved this problem.
What was happening? Something stupid (as usual):
'Inherits' attribute was missing in the CreateTicket.aspx page declaration, so the CreateTicket.aspx.cs wasn't bound as the partial class, even using the CodeBehind attribute.
Does CreateTicket.aspx inherit from WebService?
Even if it does, your class should also have the ScriptService attribute on it, so that .NET generates additional classes to assist in calling it from JavaScript.
Note: This only applies to non-WCF web services. WCF adds in its own attributes for doing web services.
If you have .NET 3.5 or newer, you can also set up a WCF service.
There's a quick guide on CodeProject on how to set up the OperationsContract and DataContract annotations on your classes in order to create said service.