Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ASP.NET MVC return a javascript response like Ruby on Rails can?

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?

like image 820
BeachRunnerFred Avatar asked Mar 08 '26 22:03

BeachRunnerFred


2 Answers

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

like image 56
Andrey Avatar answered Mar 11 '26 12:03

Andrey


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);
    }
});
like image 44
Darin Dimitrov Avatar answered Mar 11 '26 13:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!