Following is the next post in the Programming section of this blog and 2nd post in MVC

Scenario : While working in my first MVC project , I was trying  to add functionality in a menu embedded in MVC View (city.cshtml). The view was having details of a particular city and in menu there were certain menu items like 'CRIME' , 'WEATHER' etc for that City.

According to the menu item clicked , there was need of some server side processing and according to that processing result , I had to show some information in the left side panel keeping the whole View (page) intact means I didn't want to refresh whole of the View. So one of the several approaches can be to call controller method (server side processing) via javascript or Jquery.

AIM: Calling controllers method using Jquery / Javascript 

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;
               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++) {

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.

Hope this will help. Happy Coding.

You may also be interested in 
For exploring more in programming on this blog click here 


Post a Comment