How to return Javascript from an ASP.NET 5 MVC 6 controller action

I need one action to return a JavaScript fragment.

In MVC 5 we have:

return JavaScript("alert('hello')"); 

but in MVC 6 we do not.

Is there any way to do this now?

+5
source share
3 answers

This can be achieved by returning the ContentResult MSDN.

 return Content("<script language='javascript' type='text/javascript'>alert('Hello world!');</script>"); 

or other way will use ajax

 return json(new {message="hello"}); $.ajax({ url: URL, type: "POST", success: function(data){alert(data.message)}, }); 
+8
source

I think we can implement JavaScriptResult ourselves, as it is not officially supported. This is easy:

 public class JavaScriptResult : ContentResult { public JavaScriptResult(string script) { this.Content = script; this.ContentType = "application/javascript"; } } 
+2
source

ASP.NET MVC 6 does not currently support JavaScriptResult , as in MVC 5. An interesting discussion of this can be found here (there are some solutions for your problem): https://github.com/aspnet/Mvc/issues/2953

Personally, I believe that sending JS code to the client is bad (send the data that the JS needs to the client and then make function calls there), but it seems that there is a right situation for this (look at the last comment).

0
source

All Articles