Reputation: 4425
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
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
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
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