ASP MVC Ajax Controller pattern?
Posted
by Kevin Won
on Stack Overflow
See other posts from Stack Overflow
or by Kevin Won
Published on 2010-04-14T19:41:54Z
Indexed on
2010/04/14
23:33 UTC
Read the original article
Hit count: 536
My MVC app tends to have a lot of ajax calls (via JQuery.get()). It's sort of bugging me that my controller is littered with many tiny methods that get called via ajax. It seems to me to be sort of breaking the MVC pattern a bit--the controller is now being more of a data access component then a URI router.
I refactored so that I have my 'true' controller for a page just performing standard routing responses (returing ActionResponse objects). So a call to /home/ will obviously kick up the HomeController class that will respond in the canonical controller fashion by returning a plain-jane View.
I then moved my ajax stuff into a new controller class whose name I'm prefacing with 'Ajax'. So, for example, my page might have three different sections of functionality (say shopping cart or user account). I have an ajax controller for each of these (AjaxCartController, AjaxAccountController). There is really nothing different about moving the ajax call stuff into its own class--it's just to keep things cleaner. on client side obviously the JQuery would then use this new controller thusly:
//jquery pseudocode call to specific controller that just handles ajax calls
$.get('AjaxAccount/Details'....
(1) is there a better pattern in MVC for responding to ajax calls?
(2) It seems to me that the MVC model is a bit leaky when it comes to ajax--it's not really 'controlling' stuff. It just happens to be the best and least painful way of handling ajax calls (or am I ignorant)?
In other words, the 'Controller' abstraction doesn't seem to play nice with Ajax (at least from a patterns perspective). Is there something I'm missing?
© Stack Overflow or respective owner