Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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 ?

like image 900
Beetlejuice Avatar asked Sep 18 '15 19:09

Beetlejuice


People also ask

Can we call JavaScript function from controller in MVC?

There is no direct way to call JavaScript function from Controller as Controller is on Server side while View is on Client side and once the View is rendered in Browser, there is no communication between them.

Can we use JavaScript in ASP NET MVC?

JavaScript can be used in asp.net mvc.

Where do I put JavaScript code in MVC?

You can create the Scripts folder in the root folder of your MVC project, and then save all JavaScript files in the Scripts folder. You can call functions defined in JavaScript files by using script blocks or event handlers.


2 Answers

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)},    
    });
like image 165
warrior Avatar answered Oct 03 '22 05:10

warrior


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";
    }
}
like image 35
Maxim Avatar answered Oct 03 '22 03:10

Maxim