Beetlejuice
Beetlejuice

Reputation: 4425

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

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 ?

Upvotes: 8

Views: 18346

Answers (3)

Maxim
Maxim

Reputation: 13468

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";
    }
}

Upvotes: 6

warrior
warrior

Reputation: 616

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

Upvotes: 9

Vladislav Karamfilov
Vladislav Karamfilov

Reputation: 471

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

Upvotes: 0

Related Questions