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 ?
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.
JavaScript can be used in asp.net 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.
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)},
});
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With