开发者

Javascript in Controller

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

I t开发者_JAVA百科ried 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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜