Reputation: 1879
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
Reputation: 9954
You can read this post
The ASP.NET MVC framework supports several types of action results including:
5. JavaScriptResult – Represents a JavaScript script.
Hope it helps
Upvotes: 0
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