8

I need one Action return a JavaScript fragment.

In MVC 5 we have:

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

but in MVC 6 we don´t.

Is there a way to do this now ?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84

3 Answers3

9

This can be achieved by returning ContentResult MSDN

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

or other way would be making use of ajax

return json(new {message="hello"});  

 $.ajax({
        url: URL,
        type: "POST",
        success: function(data){alert(data.message)},    
    });
Travis J
  • 81,153
  • 41
  • 202
  • 273
warrior
  • 606
  • 2
  • 8
  • 23
  • 1
    Can you please include an explanation with this as well. Code only answers are typically frowned upon because they lack reasoning. Perhaps include a link to MSDN or something that references Content? – Travis J Sep 18 '15 at 19:05
  • The first option does not work with mvc 6. Nothing happens, at all. – Beetlejuice Sep 18 '15 at 19:31
  • Can you add more to your code rather than a simple return statment, client side, controller code. I would prefer second option though. – warrior Sep 18 '15 at 19:37
  • Actually I need to render a partial view and present it in a bootbox control. – Beetlejuice Sep 18 '15 at 19:48
  • where do I put the ajax code. I don't have a view. I just want to display alert. – Ashenafi Semu Mar 21 '17 at 08:51
4

I think we can implment JavaScriptResult ourselves since it is not supported officially. It is easy:

public class JavaScriptResult : ContentResult
{
    public JavaScriptResult(string script)
    {
        this.Content = script;
        this.ContentType = "application/javascript";
    }
}
Maxim
  • 13,029
  • 6
  • 30
  • 45
0

Currently ASP.NET MVC 6 doesn't support JavaScriptResult like in MVC 5. An interesting discussion for this can be found here (there's some solutions for your problem too): https://github.com/aspnet/Mvc/issues/2953

Personally I think that sending JS code to the client is a bad thing (send the client the data that the JS needs and then perform the functions invocations there) but it seems that there's a valid situation for this (look at the last comment).

  • This will be a challenge for my actual project. But I will give a try. – Beetlejuice Sep 18 '15 at 19:31
  • 3
    Sending??? No! It should be used for sharing of dynamically create JS using site endpoint. For example for dynamically created constants. – Maxim Jul 19 '16 at 05:44