Blog from Saravanan Arumugam

Let us talk about Technologies

Tag Archives: MVC 3

Working with JSON objects in ASP.NET MVC

In this paper I am going to explain, a simple way of working with javascript, JSON objects to make call to MVC Action through Ajax.


A little introduction to Object representations in Javscript

In javascript, a value to an object can be provided in many ways.

1. Simple assignment

rows = 24;

2. Assignment in Json style

“columns” : “12”

3. Representation of Object

 var newBlog = {blogName: "Working with Json", Content: "….", Index: 51 }

Note that braces represent that it contains an object.

4. Instantiating an Object with “new” keyword

var myString = new String();

5. Representation of Array

var styles = [
{Height:”20”, Width: “50” },
{Height: “30”, Width: “50”},
{Height: “10”, Width: “40”}


Note that the square brackets represent the Array of object/variables.

From javascript object, JSON object can be generated by using JSON.stringify() method. An implementation of JSON.stringify() can be seen in the example at the end of the paper.


Planning the Javascript object for MVC call

MVC includes a default support for JSON binding. When you pass a Json object from client side, the MVC runtime makes all its attempts to understand it, and translate that into a CLR object for you.

For example,

To represent the following class in MVC server side

public class RequestPosition
	public int RequestID { get; set; }
	public int Position { get; set; }

javascript object has to be,

var position = { RequestID : 102, Positon=1 }

Note that the position object has two members and their names (RequestID, Position) are the same as the RequestPosition class’s properties.


To receive this javascript object the MVC action should have the following syntax.

public JsonResult ProcessRequestPosition(RequestPosition position)

Note that the Action has a parameter with the same name as the javascript object we prepared in the client side. When MVC runtime sees a parameter, it looks into the ViewData, query string, Json data etc. to find the value of its parameters.


A complete implementation

Code on the client side

$(document).ready(function () {

	$("#Save").on("click", function (){
		var requestSequence = [{ RequestID: "10", Position: 5 },
			{ RequestID: "11", Position: 8}];
		requestSequence[requestSequence.length] = { RequestID: "12",Position: 9};

		$.ajax("/Queue/SaveRequestSequence", {
			type: "application/json; charset=utf-8",
			dataType: "json",
			success: function (message) { alert(message); },
			error: function () { alert('Oops, the operation failed'); }


Note that requestSequence is an array and is initialized with 2 objects first. Then a third object is added using the index based assignment “requestSequence[requestSequence.length]. requestSequence.length in the place of index ensures that you always add the value at the end of the array.

Here $.ajax does the magic of calling the SaveRequestSequence action from client side.


Code on the server side

	public JsonResult SaveRequestSequence(RequestPosition[] requestSequence)
		//Save Operation
		return Json("Sequence saved successfully!");

Index in IEnumerable

When we use the IEnumerable interface, its usually hard to get the index of the item.

For example, I need to display a dropdown list in a page that uses MVC 3. I can use the CurrentCulture class to get the array of month names. But I want to set the integer as the value representing the month.

<select id="MonthSelection" name="MonthSelection">
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
    <option value="4">Apr</option>
    <option value="5">May</option>
    <option value="6">Jun</option>
    <option value="7">Jul</option>
    <option value="8">Aug</option>
    <option value="9">Sep</option>
    <option value="10">Oct</option>
    <option value="11">Nov</option>
    <option value="12">Dec</option>
    <option value="13"></option>

The choice I had was this. I couldn’t use the foreach since it would not provide me the ability to get the index of the item. So I am left with for() loop. However, look at the code below, isn’t that too much of coding for a simple thing?

Dictionary<int, string> months = new Dictionary<int, string>();

for (int index = 0;

    index < CultureInfo.CurrentCulture





    months.Add(index + 1,






Using the for() loop is not comfortable all the time.



Linq provides a solution to this situation. In a IEnumerable, if you want the index of the item, use the projection (Select) with a second parameter to the lambda expression. The second parameter is usually the index of the item in the collection.

.AbbreviatedMonthNames.Select((month, index) 
           => new { Key = index + 1, Value = month })

Now the whole code show on the previous example is shrunk to a single line. Isn’t that great from Linq?