Showing posts with label MVC 5 Javascript Ajax Call. Show all posts
Showing posts with label MVC 5 Javascript Ajax Call. Show all posts

Monday 28 September 2015

Calling Controller Method from Javascript using $.ajax in MVC 5

Javascript function to call Controller Method 

@section  Scripts
{


<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

   <script type="text/javascript">

       $(document).ready(
           function () {
               $("#btn").click(
                   function () {

                       $("#showcontent").text("Loading...Ajax content").css({ "color": "red" });

                       $.ajax(
                           {
                               url: "/home/AjaxCall",
                               type: "GET",
                               success : function(data)
                               {
                                   $("#showcontent").text(data).css({ "color": "green" });
                               }
                            }
                           );

                   }

                   );

           }

           );

    </script>

}

<h2 id="showcontent"></h2>
<button id="btn" >Show details</button>

Add these lines  in any of your sample views and mention the controller method in the url section of ajax block which is highlighted ..

Here is the controller method  




 [System.Web.Mvc.HttpGet]
        public string AjaxCall()
        {
            Thread.Sleep(5000); // Thread is for showing the ajax loading call on view
            return "AjaxCall";

        }

Use this code in your controller ..

Output : 

1. Initially the view will look like this  :


 2. After Pressing the Show details , the ajax call will go to the controller.
      then the below screen will appear.



   3. Once the call is reached to controller and after 5 seconds  , the controller method will return with        'AjaxCall'. '