Jaqen H'ghar
Jaqen H'ghar

Reputation: 1879

Javascript in Controller

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

Upvotes: 1

Views: 3490

Answers (2)

SDReyes
SDReyes

Reputation: 9954

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

Upvotes: 0

Branislav Abadjimarinov
Branislav Abadjimarinov

Reputation: 5131

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

Upvotes: 1

Related Questions