How to Call Controller Actions using JQuery in ASP.NET MVC

后端 未结 5 2071
粉色の甜心
粉色の甜心 2020-11-29 05:28

I\'ve been reading on this for a while and found that you can call a controller action by using:

$.ajax(\"MyController/MyAction\", function(data) {
    alert         


        
相关标签:
5条回答
  • 2020-11-29 05:39

    We can call Controller method using Javascript / Jquery very easily as follows:

    Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'

    public JsonResult SubMenu_Click(string param1, string param2)
    
        {
           A[] arr = null;
            try
            {
                Processing...
               Get Result and fill arr.
    
            }
            catch { }
    
    
            return Json(arr , JsonRequestBehavior.AllowGet);
    
        }
    

    Following is the complex type (class)

     public class A
     {
    
      public string property1 {get ; set ;}
    
      public string property2 {get ; set ;}
    
     }
    

    Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.

    function callControllerMethod(value1 , value2) {
        var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 &param2=value2'
        $.getJSON(strMethodUrl, receieveResponse);
    }
    
    
    function receieveResponse(response) {
    
        if (response != null) {
            for (var i = 0; i < response.length; i++) {
               alert(response[i].property1);
            }
        }
    }
    

    In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.

    receieveResponse is the callback function receiving the response or return value of the controllers method.

    Here we made use of JSON , since we can't make use of the C# class object

    directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:

    Json(arr , JsonRequestBehavior.AllowGet);
    

    and returned that Json object.

    Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.

    For more detaill click here

    0 讨论(0)
  • 2020-11-29 05:53

    You can easily call any controller's action using jQuery AJAX method like this:

    Note in this example my controller name is Student

    Controller Action

     public ActionResult Test()
     {
         return View();
     }
    

    In Any View of this above controller you can call the Test() action like this:

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "@Url.Action("Test", "Student")",
                success: function (result, status, xhr) {
                    alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
                },
                error: function (xhr, status, error) {
                    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                }
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-11-29 05:55

    the previous response is ASP.NET only

    you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

    and then a similar block of code but simpler...

    $.ajax({ url: '/Controller/Action/Id',
             success: function(data) { alert(data); }, 
             statusCode : {
                 404: function(content) { alert('cannot find resource'); },
                 500: function(content) { alert('internal server error'); }
             }, 
             error: function(req, status, errorObj) {
                   // handle status === "timeout"
                   // handle other errors
             }
    });
    

    I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

    ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

    0 讨论(0)
  • 2020-11-29 06:00

    You can start reading from here jQuery.ajax()

    Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.

    $.ajax({
        // edit to add steve's suggestion.
        //url: "/ControllerName/ActionName",
        url: '<%= Url.Action("ActionName", "ControllerName") %>',
        success: function(data) {
             // your data could be a View or Json or what ever you returned in your action method 
             // parse your data here
             alert(data);
        }
    });
    

    More examples can be found in here

    0 讨论(0)
  • 2020-11-29 06:05

    In response to the above post I think it needs this line instead of your line:-

    var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' &param2='+value2
    

    Or else you send the actual strings value1 and value2 to the controller.

    However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.


    Here is a working solution. For the cshtml page:-

       <button type="button" onclick="ButtonClick();"> Call &raquo;</button>
    
    <script>
        function ButtonClick()
        {
            callControllerMethod2("1", "2");
        }
        function callControllerMethod2(value1, value2)
        {
            var response = null;
            $.ajax({
                async: true,
                url: "Logging/SubMenu_Click?param1=" + value1 + " &param2=" + value2,
                cache: false,
                dataType: "json",
                success: function (data) { receiveResponse(data); }
            });
        }
        function receiveResponse(response)
        {
            if (response != null)
            {
                for (var i = 0; i < response.length; i++)
                {
                    alert(response[i].Data);
                }
            }
        }
    </script>
    

    And for the controller:-

    public class A
    {
        public string Id { get; set; }
        public string Data { get; set; }
    
    }
    public JsonResult SubMenu_Click(string param1, string param2)
    {
        A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
        return Json(arr , JsonRequestBehavior.AllowGet);
    }
    

    You can see the time changing each time it is called, so there is no caching of the values...

    0 讨论(0)
提交回复
热议问题