BlueLemonCode.Com

Yet Another Tech Blog

Get data from controller method in JavaScript using JQuery

Introduction

While working in web application, it is often required to get data/value from server side and do the processing or display result in javascript. It is more important to get this server side data asynchronously. Here, we are going to see, how to achieve it in MVC Asp.net

Background

In Asp.net web form, it is easy to use call page method or web service to get data asynchronously from server side. Use of Ajax update panel makes the things even more easier. But in case of MVC there is disconnection between view and controller also, there are no script manager proxies available. However, MVC Ajax is still very flexible and use JQuery makes it very easy task.

Article Body

The main part of getting data from server side is done using jQuery get method. You can read more about jQuery get here.

lets create a demo project to demonstrate the functionality. Create a default MVC project and in default Index.aspx page create 2 input type text fields and a button. One more empty div is added to display result. The view tags looks like this

<p style="width: 40%">
        Enter operand1 and operand2 and click on Get sum button<p>
        <input type="text" id="txtValue1" />  + <input type="text" id="txtValue2" />
        <p>
        <input type="button" onclick="return Getsum()" value="Get sum" />
        <div id="result" style="width:30%">
        </div>
</p>

The demo will consist of two text fields where two values can be entered; upon clicking on button, the sum of two entered values will be displayed in div. The only thing is the calculation will take place in server side in action method and the action method is called asynchronously.

As you can see in above code, we have called Getsum() function on click of a button. Getsum is the Javascript function. Now, create a Javascript function Getsum() with code as below.

<script type="text/javascript">
    function Getsum() {

        $.get("/Home/CalculateSum",
      {
          val1: $("#txtValue1").val(),
          val2: $("#txtValue2").val()
      },
      function (data) {
          $("#result").append(data);
      }
      );
      return false;
    }
</script>

The main part in above code is call to the jQuery $.get() function. The function accepts three parameters. The first parameter is in format "/ControllerName/ActionName", the second parameter contains list of input parameters in format such as

{
 firstParamName: firstParamValue,
 secondParamName: secondParamValue
}

the third parameter indicates a callback function which would be executed if request succeeds.

Now, in HomeController class, create a ActionResult method named CalculateSum as below

VB.Net

Public Function CalculateSum(ByVal val1 As String, ByVal val2 As String) As ActionResult
        Threading.Thread.Sleep(5000)
        Return Content((Convert.ToInt16(val1) + Convert.ToInt16(val2)).ToString())
End Function
C#

public ActionResult CalculateSum(string val1, string val2)
{
	System.Threading.Thread.Sleep(5000);
	return Content((Convert.ToInt16(val1) + Convert.ToInt16(val2)).ToString());
}

As a demo, i have added a delay in execution of ActionResult by 5 seconds by using Thread.sleep(). In real scenario it may have some lengthy database/file operation. Note that the string is returned using ContentResult which is then received in onSuccess callback method of jQuery get. Finally data sum of two values is displayed in div below.

This comes very handy and you can find yourself using asynch call to ActionResult very frequently during MVC application development.

If you feel anything is missing in the explanation, please drop a comment :)