Latest Asp.Net MVC RC permits to return JavaScript ActionResult.
I'd like to dynamically generate from the controller the Jquery script code associated to perform the classical $.ajax calls to the controller for Create Read Update Delete operations in ajax instead of classical get/post form actions.
Should I generate the javascript code at design time (like is now with T4 templates) or at runtime?
I know this will break clear separation from view and controller but is there a better way?
2 Answers
In my opinion this is a bad technique to return javascript action result. You'll receive code mess like when you use inline styles for html elements. Why not to write js in separate file and just include it in page? In order to perform some actions after your ajax call you easily can use a callback. If you need to specify which elements you need to update or delete or something else you can use JsonResult and $.getJSON or $.post(url, data, callback, 'json'). In order to ajaxify your forms you may use jquery.form plugin. Also look at jquery.jframe plugin which provide functionality to update some other elements with a responce from request.
Comments
Most of the time when I create a controller method that returns a JsonResult I then end up writing the same boilerplate javascript code to access it that I have written dozens (maybe hundreds) of times but with different parameters and a different callback function passed in. I have been thinking that this is a perfect opportunity for code generation. I am still looking into this but here are a couple of resources I have come across:
- A Steve Sanderson blog post looking at using T4 to scaffold out an AJAX grid controller which includes some generated javascript that wires up the grid. http://blog.stevensanderson.com/2011/04/08/mvcscaffolding-scaffolding-custom-collections-of-files/
Jayrock (http://jayrock.berlios.de/) is a JSON RPC framework that helps you create services that return JSON and generates it's own proxy javascript classes that handle the ajax coding to make synchronous and asynchronous calls to server. Example from the project site:
var s = new HelloWorld();
alert("sync:" + s.greetings());
s.greetings(function(response) { alert("async:" + response.result) });
Additionally it generates test pages similar to the the ones that .NET webservices did. I have used this lib in the past and found it effective. While I like the idea of continuing to keep related code in the controller I may go back to this for the convenience factor so I can spend more time on the code I can't have a computer generate.
- Lastly, Phil Haack pasts about doing the very thing we are talking about here (I haven't tried this yet), http://haacked.com/archive/2011/08/18/calling-asp-net-mvc-action-methods-from-javascript.aspx