Hello. I'm diving into ASP.NET MVC and I'm coming from a Ruby on Rails background. I'm trying to understand how ASP MVC handles AJAX functionality and, after reading some of the tutorials on the ASP website, it appears they implement AJAX functionality very differently. One of the ways that RoR handles AJAX functionality is by returning ruby-embedded javascript code that is executed as soon as it is received by the browser. This makes implementing AJAX really simple and quite fun. Can ASP.NET MVC return a javascript response?
+4
A:
just user return JavaScript(script)
You would have to execute the java script manually on the View
To be more specific you can make the controller action return type JavaScriptResult
Andrey
2010-10-20 16:42:01
Thanks, that seems very simple and similar to what I'm used to with RoR. Here's a little blog article I found related to the JavaScriptResult type that seems worth mentioning http://devlicio.us/blogs/billy_mccafferty/archive/2009/02/07/beware-of-asp-net-mvc-javascriptresult.aspx
BeachRunnerJoe
2010-10-20 16:59:11
+3
A:
What you are talking about is called javascript generators in the RoR world and there's no equivalent in the ASP.NET MVC world. Here's a blog post that illustrates the basics of implementing a Rails-like RJS for ASP.NET MVC (the blog post uses prototypejs
but could be easily adapted to work with jquery
).
Here's another approach using jquery:
public ActionResult Foo()
{
return Json(new { prop1 = "value1", prop2 = "value2" });
}
and to consume:
$.getJSON('/home/foo', function(result) {
// TODO: use javascript and work with the result here,
// the same way you would work in a RJS like template
// but using plain javascript
if (result.prop1 === 'value1') {
alert(result.prop2);
}
});
Darin Dimitrov
2010-10-20 16:42:05
Hey Darin, is there any reason I'd want to use the approach presented in that blog article instead of using the built-in approach that @Andrey pointed out? Thanks again!
BeachRunnerJoe
2010-10-20 16:57:37
It depends on your requirements. The approach presented by @Andrey is good but you have to generate the javascript manually, including loops, ifs, ... as a string and pass it to the view instead of having some RJS like language in a real template. So you might end up writing javascript in your controller which IMHO is bad.
Darin Dimitrov
2010-10-20 17:04:41
@BeachRunnerJoe, please see my update for an alternative approach.
Darin Dimitrov
2010-10-20 17:09:41
+1
A:
Also worth taking a look at is JsonResult which extends ActionResult. I usually use this when making AJAX requests for data of some sort.
jamesaharvey
2010-10-20 16:53:01