views:

379

answers:

5

I am looking for a reliable technique for adding Ajax to a working ASP.NET MVC application. I want to use jQuery, and understand how to use the ajax functionality from jQuery. What I need to know is how I should write my controller so that I can run the site without javascript, but at the same time make ajax calls possible without the need for a seperate view, seperate controller or any kind of route hack. My goal is to have a working application enhanced when javascript is enabled without the need to duplicate or recreate elements of the app.

Thanks in advance.

+2  A: 

See this question for pointers.

But generally you do want ajax to duplicate features. But duplicate with a nicer user experience.

IainMH
+1  A: 

Typically you would create your site so that it works without JavaScript being enabled. Then you would add the unobtrusive JavaScript needed to enhance your site with Ajax e.g. adding event handlers for links, form submits, etc. to make GET / POST requests and update your UI accordingly.

The only changes you would need in your MVC app would be to handle the Ajax requests and return the data as JSON, XML, etc.

Ian Oxley
A: 

I understand that I want to build my site and then add the javascript. What I am looking for is the proper way to write the code in my controller action to handle both a ViewResult for standard requests, and a JsonResult for Ajax requests.

A: 

@IainMH - By "without the need to duplicate or recreate elements of the app", I was talking about code. I don't want to have to write multiple views or special controllers just to handle the ajax calls. I want a way to modify my controllers to handle the standard requests as well as the Ajax requests.

As long as the ajax is calling the same methods, you should be ok.
IainMH
A: 

in your controller (derived from Controller), you can call Request.IsMvcAjaxRequest() to check if the request is a normal POST or an AJAX request. This will be true if the request was created from a an AjaxForm submit or an AsyncHyperlink. The Ajax form can be made visible by javascript, along with hiding the standard form.

Matthew