Integrating jQuery AJAX with .NET - asp.net

I want to make an ajax call from jQuery to my server. Basically, I want the request to be sent as a POST with a content-type of x-www-form-urlencoded and the corresponding parameters (parameter1=X&paramter2=Y&parameter3=Z). I want the response to be JSON.
The server environment is .NET. I have been experimenting with the three methods below, but have not been able to get one to work quite right.
ASPX - Using an aspx to process and return JSON, I can get it to work, but I need to serialize the JSON myself. This is possible, but I was hoping for something more convenient. Also, correct me if I'm wrong, but I would imagine that aspx pages have a lot of extra overhead involved since they are expected to do more than just execute a method and return simple JSON.
ASMX and WCF - With asmx and WCF, I can get it to return JSON, but only if I send JSON in the request.
What is the best server side "framework" to use for this request / response type? .aspx, .asmx, or WCF? Since I have been able to at least get aspx to work for this, is that even an appropriate approach?
I've seen other products out there that expose an API via a web service and use a name / value querystring request format with a JSON response type, but this seems to be a difficult feat to accomplish in .NET.

You're right that ASPX pages bring extra overhead. Even if you're not using the WebForms framework at all, requests to ASPX pages still must filter through the entire page lifecycle.
If you prefer that sort of low-level approach, reading QueryString parameters and responding with manually serialized JSON, an ASHX HttpHandler would probably be the best solution.
Personally, I prefer ASMX services. Sending JSON parameters in isn't very difficult (and you'll probably end up doing that anyway once you begin sending nested objects or collections, which is a mess via simple key/value pairs), and it's nice to avoid the needless ceremony of deserializing and serializing during every request.
People will tell you WCF is the correct solution since it's newer, but .NET 4's WCF isn't currently a great fit when you're using jQuery. It's not as flexible when dealing with DateTime and Enum types, and it has unwieldy Dictionary serialization. WCF's new WCF Web Api solves those problems though if you want to try something a bit ahead of the curve.

I've used.
.aspx -> just exactly the way you are doing it
.ashx -> similar to the .aspx except less overhead in the page lifecycle.
.asmx & wcf -> what's wrong with passing JSON in the request?
MVC -> return JsonResult. This one is my favorite when I'm not making an entire
API (for that I use WCF), but instead I just need one or two requests
to return JSON. This, of course, assumes that the entire site is
written using MVC, otherwise it would be overkill to install the
framework for just a few calls.

If you are okay going down the WCF route, may I suggest you look at the WCF WebAPI project from Microsoft. This project sits on top of WCF and provides some niceties and simplifications when it comes to client access (.NET code or jQuery Ajax). Here is a walkthrough using jQuery to POST form-urlencoded data. There are other walkthroughs demonstrating other related tasks there as well.
These services can be hosted like any other WCF service, and even hosted right within the same ASP.NET project as the rest of your site.
At this time, the project is in early development and has some "Go-Live" restrictions, but depending on your project needs, this may work out great, it has for us.

Related

Making calls to a Stand-Alone Web API to populate ViewModels in ASP.NET MVC

Lets say I have a standalone ASP.NET Core Web API as its own project (since I don't want to merge it w/ my MVC app)
I now want to create an MVC web application (another project, but same solution) that will make calls to the API. I am aware that for ajax requests I will directly call the API through JavaScript which is straight forward.
However, I am a bit confused as to how the MVC controller would make calls to the same API to populate the ViewModel and send to the View when a user requests a page i.e. http://myurl/books/1
I am aware that if I was using something like Angular which is fully client-side I wouldn't be running into this issue.
That's a good question. There's three different approaches that I can think of:
The first is to call the same API from your MVC controller with a HTTPClient object. Might seem a bit weird calling "yourself" on the server side but it works. In my opinion this isn't a great solution, because you're losing type-checking and you'll also making an unnecessary call over the network, and you also have to parse and convert the response back from WebAPI to your .net objects.
The second approach is to move all of the logic that's inside the API into a new project and compile it all down to a DLL. Your Web Api can then call the code inside the library and your MVC project can do it too. A pretty good approach.
The third approach is to do what you've suggested - don't populate the Model at all on the server side inside your MVC project and just do it all from the client side. Yes, this will work great with Angular but you can also do this yourself using bog-standard JQuery or Knockout. This approach means much more client side javascript to write (use Typescript!) but you'll end up with a much nicer separation of concerns and cleaner solution.

ASP.NET Handler (ashx) vs MVC Controller Action for downloading files

We have an application that uses webforms for some older web app pages, but also contains MVC functionality for some of the newer features. We have some new requirements for downloading files that will have to be processed on the server (not direct links to static files on the web server).
I haven't seen anything to indicate if there is a reason one should use an ASHX handler over just using an MVC controller and operating on the response object and returning EmptyResult() at the end of the action method.
Is there a best-practice for this with MVC? Should ASHX handlers be left for WebForms or is there some benefit they provide over using MVC for this type of file download feature?
The performance of HttpHandler is better since it is more bare-metal than MVC actions (just a few extra steps, but still).
Besides that, I see no reason why you should choose one over the other for performance reasons. MVC has some nice features you might want to use, like caching and authorization attributes.
If you choose to use MVC, use results that are specifically built for file handling, like FileStreamResult or FileContentResult.
Well, an ASHX can be a bit more contained and specific... however, there is something to be said about having all your code and logic in your main application.
There is no technical reason to do one over the other, to my knowledge with MVC nowadays. With WebForms it was harder to stream large files, but with MVC you can do that pretty easily (so you don't have to load the whole file into memory first). Also, given modern Async methods you don't have to worry so much about tying up worker threads and what not for scalability.
It's really up to you. Even if you wanted to separate it into its own module, nowadays it might make more sense to make it an owin module rather than an ashx. It's more about how you want to design your app.

Is It Performance Rich to use Web Services called via jquery ajax method in ASP.Net?

I have seen that ASP .Net Code Behind files are really slow. I have used local web services which I call from jquery ajax function and they are fast. But I am still confused? Should i display dynamic data from code behind or web services?
I let my web service return a JSON Object and I assign relevant elements from that JSON object to different html elements like (image, div etc.)
You need to weigh several things..
If you are dealing with a low-traffic, internal web application, perhaps server-side postbacks are the way to go. Often you'll find that there's less code you'll have to write in this case.
If you are working on an external, public, high-traffic web application, perhaps AJAX is the way to go. That way you avoid posting back entire ViewState and running through the full page lifecycle. This may result in more front-end code, but is less load on the web server.
Keep in mind that client-side data binding is a very viable solution these days, with the help of such things as jQuery Templates. So that helps bind data returned from AJAX calls to tables and other elements.
As far as web services go, they are great for when you're sharing data/functionality between different systems. If you don't foresee doing that for this particular application, then perhaps there's no need to over-engineer it - keep it simple with either MVC and Action methods that support AJAX calls out of the box, or get familiar with PageMethods.
I'm sure there are other pros/cons I haven't mentioned, but this is the first thing that came to mind.
ASP.NET classic life cycle and postback is the base of Microsoft Click&Go philosophy. It is not designed to be fast even if it suits in most cases.
AJAX plus Web Services architecture is good way to improve server performances and dynamicity. It may not improve client performances, may increase the network load if bad designed and complicate a website architecture.
Another possible orientation is ASP.NET MVC, where old life cycle and postback is ancient history.
Like Kon said, mixity is probably the best way at the moment : MVC+AJAX or ASP.NET+AJAX where classic client<->server requests are used for common functionnalities and AJAX requests brings dynamicity with small requests for friendly functionnalities.
Note that most users on the planet are using Internet Explorer who have the worst javascript engine on the planet ;)

PageMethods or Generic Handler?

I am making a site where users can reply to topics, open topics, etc. and when the user sends a message, I don't want to postback; it's ugly.
I'm using generic handlers right now but I am having some problems with it. Like updating GridView using UpdatePanel when XMLHttpRequest's onreadystate is changing.
I decided to use PageMethods but I also wanted to ask you.
Which is better, faster and more useful: PageMethods or Generic Handlers?
I don't think there would be much difference between the speed of Page methods and HTTP Handlers. However if you're worried about your application's performance, you should benchmark each option and choose what's best for you.
To answer the question, which is better or more useful, basically within the ASP.NET context you have three options, each with their pros and cons:
Page methods - all your code is contained in single Page, which is fine if the code is only used by that page. You should probably implement methods that return page-specific HTML snippets as Page methods. However if we are talking about reusable code, such as "Save Topic" or "Get Topics", you might want to consider externalizing this code elsewhere. I guarantee that as your application grows, you'll need those methods elsewhere in your application end as well.
Generic HTTP handlers - are lightweight, and great for code you need to call often throughout your application. Most often generic handlers are implemented to serve content, and I don't know what the best practice around this topic is, but to me POST ing to a generic handler to save data has a distinct smell. You'll also find that for related functionality (Save, Get single, Get many, etc.) you'll end up with a swarm of handlers, or a handler with a giant switch statement and a fuzzy contract based on query string and POST parameters. I wouldn't recommend this option to implement extensive AJAX application. For small bits and pieces it might suit your needs.
ASP.NET web services (or WCF) - The third option you did not mention in your questions are ASP.NET web services (.asmx). You can easily include them in your existing ASP.NET application without any additional framework dependencies. They offer a good balance between the options 1 and 2. On one hand you get reusability throughout your application, and even outside your application if you so choose, which Page methods cannot provide. On the other hand you can neatly bind together related functionality in meaningful ways, which tends to get messy with generic handlers. You can also interact with the services using SOAP XML, JSON or HTTP POST / Plaintext as needed.
And the wildcard option here is: Use ASP.NET MVC and jQuery. If you're looking to build a lean and mean web application and you generally find postbacks ugly, and you find stuff such as what exactly happens when the xmlhttprequest changes readystate interesting, it might provide you with a better experience overall. Maybe not for this project, but for the next one.
If you mean with generic handlers web service endpoints then you can make the following distinction:
You can use PageMethods if the functionality only needs to be available on that page only
You can use web service endpoints if you want to reuse the functionality.
Personally I practically always use web service endpoints (in my case ajax enabled WCF).
I cannot see why you shouldn't use generic handlers. I think they are best - simple and flexible.

ASP.Net ScriptManager - Is there a smaller version?

I use the ASP.Net ScriptManager to load the scripts needed for calling WCF services via HTTP/JSON. I am optimizing the total size of my pages (including scripts) and I see that Microsoft's AJAX library is the biggest file that I have at 96KB. Is there anyway that I can get a version of this file with just the features I need loaded?
Or since I already have jquery, should I use that to call my WCF JSON service instead?
Cheers,
Jon
WCF JSON services degrade gracefully down to working as a standard webservice, so you should have no problems using jQuery to post and retrieve data from them. You may lose some of the integration bells and whistles, but as someone who has taken the path you're suggesting, I can say that I don't miss it at all.
The only problem might be if you're using advanced WCF feature like 2 way connections, or guaranteed connections.

Resources