We can easily call the controller method using Javascript / Jquery as follows:
Assume that the next Controller method to be called returns an array of some objects of the class. Let the class "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); }
Below is the complex type (class)
public class A { public string property1 {get ; set ;} public string property2 {get ; set ;} }
Now it was called by a call over the JQUERY controller. The following is a jQuery function to call a controller method.
function callControllerMethod(value1 , value2) { var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 ¶m2=value2' $.getJSON(strMethodUrl, receieveResponse); } function receieveResponse(response) { if (response != null) { for (var i = 0; i < response.length; i++) { alert(response[i].property1); } } }
In the jQuery 'callControllerMethod' function above, we develop the URL of the controller and put it in a variable called 'strMehodUrl' and call the getJSON JQuery API method.
receieveResponse is a callback function that receives the response or return value of a controller method.
Here we used JSON, since we cannot use an object of class C #
directly into a javascript function, so we converted the result (arr) in the controller method into a JSON object as follows:
Json (arr, JsonRequestBehavior.AllowGet);
and returned this Json object.
Now in the Javascript / JQuery callback function, we can use this resulting JSON object and work accordingly to display the response data in the user interface.
For more information click here.