Pass data from ASP.NET MVC view to controller with Ajax and JSON

This is an example of passing data consisting of multiple arguments from your webpage (i.e. a MVC view) to the server (i.e. a MVC Controller).
We will post the data from JavaScript with Ajax, so it means we will not request a new page from the server, just passing data to the controller. We will send the data in JSON format so it can be parsed (easy and strongly typed) in the controller.

The View

In our view, we define a Javascript function to send the data with an Ajax message.

  • In the function, first we create the array with named entries called dataToSend.
  • Somewhere on the webpage we call this javascript function with some example data consisting of 4 values of different types: “John”, 3, 75.6 and 63.9
  • The array is converted into a JSON string, called jsonData. The resulting string will result in something like:
    {"Name":"John","Id":3,"X":75.6,"Y":63.9}

  • We use a JQuery Ajax post to an URL. That means our Action function in the controller should have the ‘[HttpPost]’ attribute. The url is defined with help of URL helper class of ASP.NET MVC.
  • In the URL we specific an ‘Action’ of our controller. Here the action is named ‘SetData’. That means that in the controller we need a member function like:
    public ActionResult SetData(...)

  • We pass the JSON string as data for the post message.
  • In this example, we display a popup message with the text “Posted!” after the data has been send.

This is how the javascript source code of the view (e.g. \Views\Data\Index.cshtml) looks like. This is executed in the web browser.



...
// Call the function that send the data (consists 
// of 4 arguments) towards the controller
postData("John", 3, 75.6, 63.9)
...

function postData (name, id, x, y)
{
   var dataToSend = {  Name: name,
                       Id: id,
                       X: x,
                       Y: y };

   var jsonData= JSON.stringify( dataToSend );

   $.ajax({
             url: '@Url.Action("SetData")',
             type: 'POST',
             data: { jsonData}
          }).done(function () 
          {
	   alert("Posted!");
    	  });
}


The Controller

In the MVC controller we need the C# code to receive the JSON messages from the View.

  • Include the namespace ‘System.Web.Script.Serialization’ to use the ‘JavaScriptSerializer’.
  • Let’s define a class ‘DataClass’ that matches the data send from the view. The idea is to let the JavaScriptSerializer convert the JSON message into this class with strongly typed properties. This class is a helper class and should match the data constructed in JavaScript.
  • Create an Action that matches the URL in javascript. We define it with one argument that will hold the received JSON message in a string called ‘receivedData’.
  • Give the action the [HttpPost] attribute because we we a ‘Post’ type message and not a ‘Get’ type message.
  • Create a Javascript serializer (‘jss’) and use the generic Deserialize member function to create an object of type ‘DataClass’. The results are stored in a variable called ‘dataObject’. And that will look like this:

    dataObject.Name = "John"
    dataObject.Id = 3
    dataObject.X = 75.6
    dataObject.Y = 63.9

    This is how the C# source code of the controller (e.g. Controllers\DataController.cs) looks like. This is executed on the web server.

    using System.Web.Script.Serialization;
    
    public class DataClass
    {
       public string Name{ get; set; }
       public int Id { get; set; }
       public double X { get; set; }
       public double Y { get; set; }
    }
    
    public class DataController : IController
    {
       [HttpPost]
       public ActionResult SetData(string receivedData)
       {
          var jss = new JavaScriptSerializer();
          var dataObject = jss.Deserialize(receivedData);
          // .. do something with data object 
          return Json("OK");
       }
    }
    

Leave a comment