Call javascript from MVC controller action

后端 未结 9 1283
半阙折子戏
半阙折子戏 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条回答
  •  旧时难觅i
    2021-02-01 07:21

    You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.

    An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.

    $.ajax({
               type: "POST",
               url: "/Controller/Action", // the URL of the controller action method
               data: null, // optional data
               success: function(result) {
                    // do something with result
               },                
               error : function(req, status, error) {
                    // do something with error   
               }
           });
    

提交回复
热议问题