1

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
  • Do try to call the action via Ajax? Commented Feb 5, 2010 at 8:24

2 Answers 2

1

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...
  }             
);
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.