Call javascript from MVC controller action

后端 未结 9 1258
半阙折子戏
半阙折子戏 2021-02-01 07:04

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

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 07:33

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

提交回复
热议问题