Ajax response data in .net - asp.net

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 ");
}
});
});

Related

Make ASP.NET AJAX function call synchronous

I have an ASP.NET form that calls a web service using ASP.NET AJAX. How do I make the call synchronous?
// test.aspx
<script type="text/javascript">
function GetDescription(){
var code = document.getElementById("<%=txtCode.ClientID%>").value;
var description =
MyNamespace.MyService.GetDescription(
code, onSuccessGetDescription, null, null);
return false;
}
function OnSuccessGetDescription(result){
var txtDescription =
document.getElementById("<%=txtDescription.ClientID%>");
}
</script>
<script type="text/javascript">
$(document).ready(//function () {
$('#<%=cmdSave.ClientID%>').click(function (e) {
e.preventDefault();
if (Page_ClientValidate()){
// Populate jQuery.UI dialog box with code and description
// and then
$("#confirm-dialog").dialog("open");
}
});
}
</script>
<asp:TextBox ID="txtCode" />
<asp:TextBox ID="txtDescription" />
<asp:Button ID="cmdSave" />
// test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
txtCode.Attributes["onblur"] = "GetDescription();";
}
The answers to this question that I have seen say that I should set the async attribute to false, but I don't see how to do that here.
ASP.Net Ajax - PageMethods Synchronous call and retrieval of results says that it can't be done. I am trying to get a second opinion.
If I can't make the call synchronous, would it be legal to make GetTransaction poll until the OnSuccess function returns? What would be an efficient (i.e. not CPU-intensive) way to do that?
JQuery Asynchronous
jQuery.ajax({
url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
success: function (result) {
if (result.isOk == false) alert(result.message);
},
async: false
});

Calling C# collection using Ajax to GridView

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

WebMethod In Aspx Page Can Not Have access Allow-Origin

I have following code.It is not working for enabling CORS.Please help.I am not able to enable CORS in my Web Method on aspx page :
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("access-control-allow-headers", "content-type");
}
[WebMethod]
[ScriptMethod]
public static string Get(string data)
{
System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
System.Web.HttpContext.Current.Response.AppendHeader("access-control-allow-headers", "content-type");
return data + " 123";
}
}
// Java Script
function GetData() {
window.jQuery.support.cors = true;
window.jQuery.ajax({
url: 'http://generalservices.prop.preview.gearhost.com//Default.aspx/Get',
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'post',
data: "{ data : '12'}",
success: function (d) {
},
error: function (d) {
}
});
error : in Access-Control-Allow-Origin not allowed
Page methods are supposed to be used only from the same page where they are defined.
If you need to fetch data from different pages, I would suggest you look into Asp.Net Web api. Or you could even create a simple Generic handler (.ashx file) which you call from your page(s). The handler could deserialize the Json data, process it and return the required response. In a generic handler you can specify any/all http headers that you need.

jQuery Ajax: Parse Error Getting Result to Alert Box

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.

Load ascx via jQuery

Is there a way to load ascx file by jQuery?
UPDATE:
thanks to #Emmett and #Yads. I'm using a handler with the following jQuery ajax code:
jQuery.ajax({
type: "POST", //GET
url: "Foo.ashx",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
jQuery('#controlload').append(response.d); // or response
},
error: function ()
{
jQuery('#controlload').append('error');
}
});
but I get an error. Is my code wrong?
Another Update :
I am using
error: function (xhr, ajaxOptions, thrownError)
{
jQuery('#controlload').append(thrownError);
}
and this is what i get :
Invalid JSON:
Test =>(this test is label inside my ascx)
and my ascx file after Error!!!
Another Update :
my ascx file is somthing like this:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server">Test</asp:Label>
but when calling ajax i get this error in asp: :(
Control 'ctl00_ddl' of type 'DropDownList' must be placed inside a form tag with runat=server.
thanks to #Yads. but his solution only work with html tag.
Building off Emmett's solution
public class FooHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write(RenderPartialToString("Foo.ascx"));
}
private string RenderPartialToString(string controlName)
{
Page page = new Page();
Control control = page.LoadControl(controlName);
page.Controls.Add(control);
StringWriter writer = new StringWriter();
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Use the following jquery request
jQuery.ajax({
type: "POST", //GET
url: "Foo.ashx",
dataType: "html",
success: function (response)
{
jQuery('#controlload').append(response); // or response
},
error: function ()
{
jQuery('#controlload').append('error');
}
});
public ActionResult Foo()
{
return new ContentResult
{
Content = RenderPartialToString("Foo.ascx", null),
ContentType = "text/html"
};
}
//http://www.klopfenstein.net/lorenz.aspx/render-partial-view-to-string-asp-net-mvc-benchmark
public static string RenderPartialToString(string controlName, ViewDataDictionary viewData)
{
ViewPage vp = new ViewPage();
vp.ViewData = viewData;
Control control = vp.LoadControl(controlName);
vp.Controls.Add(control);
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
vp.RenderControl(tw);
}
}
return sb.ToString();
}
*.ascx files are rendered on the server side (inside of an *.aspx page), not the client side (where JavaScript is executed).
One option might be to create a blank *.aspx, put the user control on the *.aspx page, and then get that page via jQuery and dump the result on the page.
Edit
Based on your comment, I have another suggestion:
If you're developing a CMS style application, you should build your *.ascx controls so that they are compatible with the ASP.NET AJAX Toolkit. That will allow the users to add content to the page without doing a full refresh.
If you really want to make things nice for the user, you should check out Web Parts and ASP.NET AJAX as Web Parts were really designed so that users could customize the content on their pages.

Resources