Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually making AJAX calls in ASP.NET and C#

I want to write my own AJAX in ASP.NET, and not use the ASP.NET ScriptManager, etc.

WHY? I like doing stuff manually and knowing how stuff works from the inside, so I just want to do it for myself.

So my question is, after I make an AJAX call:

var ajaxCall = new XMLHttpRequest();
....
ajaxCall.send(null)

How can I, in C#, add in the Page_Load (or not) so that it listens for this and returns a String for example.

like image 947
Tomasz Iniewicz Avatar asked Feb 03 '23 06:02

Tomasz Iniewicz


1 Answers

Like this answer, +1 for doing it yourself.

However, I must strongly advise you to use a library like jQuery on the client-side to account for differences across browsers (and in this specific case, there are differences). It (or other libraries) will provide an abstraction you can use across all web browsers to normalize your code.

That being said, in ASP.NET, you could check to see if the call is a post back, and if it is, just write the content to the output stream.

However, I would strongly recommend against that. Rather, the call to ajax should be to another page completely, as it's providing a different purpose, a different kind of response, and therefore, deserves it's own URL.

Also, mind you, that when returning content in the form of XML or JSON (which is typical for Ajax calls, with JSON being pretty dominant now), it's important to change the ContentType property of the response to the appropriate mime type ("text/xml" for XML, "application/json" for JSON).

Note that ASP.NET MVC makes this all much, much easier, and you might want to look into using that instead of the WebForms model, as MVC is built from the ground up to handle many of these scenarios much easier. It allows you to cleanly separate methods which process page rendering, from those that provide functionality in the form of Ajax calls (and this is just one of the many benefits).

like image 113
casperOne Avatar answered Feb 05 '23 19:02

casperOne