views:

71

answers:

3

I want to write a action method returning Javascript. How to run javascript using MVC controller?

I tried the following, but it fails to work properly. It shows file download - security warning?

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult About(clsABC param)
  {
        string message = "Hello! World.";
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<script type = 'text/javascript'>");
        sb.Append("window.onload=function(){");
        sb.Append("alert('");
        sb.Append(message);
        sb.Append("')};");
        sb.Append("</script>");             
        return JavaScript(sb.ToString());   
   }

Any solution to this problem?

Thanks, Kapil

+1  A: 

You can load and execute the JavaScript with jQuery getScript method. In that case you can just write the script that you want to be executed in your action and call it with jQuery.

$.getScript("/Controller/Action", function(){
    alert('Script was loaded');
  });
});

If you load the script on button click don't forget to call preventDefault method like this. This will prevent download file dialog from showing in your case.

$('selector here').click(function(e){
    e.preventDefault();
    ...Do your stuff...
  }             
);
Branislav Abadjimarinov
A: 

Check ScriptSharp project.

Script#

It is using in ASP.NET MVC since V1.

takepara
A: 

Hi!

You can read this post

The ASP.NET MVC framework supports several types of action results including:

  1. ViewResult – Represents HTML and markup.
  2. EmptyResult – Represents no result.
  3. RedirectResult – Represents a redirection to a new URL.
  4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.

5. JavaScriptResult – Represents a JavaScript script.

  1. ContentResult – Represents a text result.
  2. FileContentResult – Represents a downloadable file (with the binary content).
  3. FilePathResult – Represents a downloadable file (with a path).
  4. FileStreamResult – Represents a downloadable file (with a file stream).

Hope it helps

SDReyes