3

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?

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 devlicio.us/blogs/billy_mccafferty/archive/2009/02/07/…
3

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);
    }
});

3 Comments

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!
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.
@BeachRunnerJoe, please see my update for an alternative approach.
1

Also worth taking a look at is JsonResult which extends ActionResult. I usually use this when making AJAX requests for data of some sort.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.