Can I call javascript function from MVC controller action (not from view page) and get return value? How?
I need to make request to server
It is late answer but can be useful for others. In view use ViewBag as following:
@Html.Raw("")
Then from controller set this ViewBag as follows:
ViewBag.DynamicScripts = "javascriptFun()";
This will execute JavaScript function. But this function would not execute if it is ajax call. To call JavaScript function from ajax call back, return two values from controller and write success function in ajax callback as following:
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
success: function(result, para) {
if(para == 'something'){
//run JavaScript function
}
},
error : function(req, status, error) {
// do something with error
}
});
from controller you can return two values as following:
return Json(new { json = jr.Data, value2 = "value2" });