Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » Ajax » General » Downloads
 
Add your own
alternative version

Working on JSON objects in jQuery and MVC

, 24 Nov 2010
This article uses a simple example to answer some common questions when working on JSON objects in jQuery and MVC.
JsonMVC.zip
JsonMVC
JsonMVC
bin
Content
Images
rubik.ico
Styles
jquery.tree.images
ajax-loader.gif
file.gif
folder-closed.gif
folder.gif
treeview-black-line.gif
treeview-black.gif
treeview-default-line.gif
treeview-default.gif
treeview-famfamfam-line.gif
treeview-famfamfam.gif
treeview-gray-line.gif
treeview-gray.gif
treeview-red-line.gif
treeview-red.gif
Controllers
Global.asax
JsonMVC.csproj.user
Models
obj
Debug
TempPE
Properties
Repositories
Scripts
Views
Home
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Working on Json Arrays in MVC</title>
    <link rel="SHORTCUT ICON"
        href="<%= Url.Content("~/Content/Images/rubik.ico") %>" />
    <link rel="stylesheet"
        href="<%= Url.Content("~/Content/Styles/Site.css") %>"
        type="text/css" />
    <link rel="stylesheet"
        href="<%= Url.Content("~/Content/Styles/jquery.treeview.css") %>"
        type="text/css" />
    
    <script src="<%= Url.Content("~/Scripts/jquery-1.4.2.min.js") %>"
        type="text/javascript">
    </script>
    <script src="<%= Url.Content("~/Scripts/jquery.treeview.js") %>"
        type="text/javascript">
    </script>

    <script type="text/javascript" language="javascript">
        var GetStudentsURL
            = '<%: Url.Action("GetStudents", "JsonOperations") %>';
        var AddAnExamBySessionURL
            = '<%: Url.Action("AddAnExamBySession", "JsonOperations") %>';
        var AddAnExamByJsonURL
            = '<%: Url.Action("AddAnExamByJson", "JsonOperations") %>';
        var StudentJson = null;
        var NoOfStudents = 3, NoOfClasses = 1, NoOfExams = 0;

        var prependZero = function (v) {
            v = v.toString();
            return (v.length == 1) ? "0" + v : v;
        };

        var dateDeserialize = function (dateStr) {
            var dt = new Date(parseInt(dateStr.substr(6)));
            return prependZero((dt.getMonth() + 1))
                + "/" + prependZero(dt.getDate())
                + "/" + dt.getFullYear()
                + " " + prependZero(dt.getHours())
                + ":" + prependZero(dt.getMinutes())
                + ":" + prependZero(dt.getSeconds());
        };

        var FixDateinJson = function (JsonStudents) {
            $.each(JsonStudents, function (i, JsonStudent) {
                $.each(JsonStudent.ClassesTaken, function (i, JsonClass) {
                    $.each(JsonClass.ExamesTaken, function (i, JsonExam) {
                        JsonExam.ExamTime = dateDeserialize(JsonExam.ExamTime);
                    });
                });
            });

            return JsonStudents;
        }

        var buildStudentTree = function (students) {

            var createTextNode = function (text) {
                var span = document.createElement("span");
                span.setAttribute("style", "margin-left: 2px");
                var tx = document.createTextNode(text);
                span.appendChild(tx);

                return span;
            };

            var root = document.createElement("ul");
            root.id = "StudentTreeRoot";
            root.setAttribute("style", "margin: 15px");
            root.className = "filetree";
            $.each(students, function (i, student) {
                var studentNode = document.createElement("li");
                //studentNode.className = "closed";
                var span = document.createElement("span");
                span.className = "folder";
                span.appendChild(createTextNode(student.Name));
                studentNode.appendChild(span);

                var classesNode = document.createElement("ul");
                $.each(student.ClassesTaken, function (i, aClass) {
                    var classNode = document.createElement("li");
                    //classNode.className = "closed";
                    span = document.createElement("span");
                    span.className = "folder";
                    span.appendChild(createTextNode(aClass.Name))
                    classNode.appendChild(span);

                    var examesNode = document.createElement("ul");
                    examesNode.className = "folder";

                    $.each(aClass.ExamesTaken, function (i, aExam) {
                        var examNode = document.createElement("li");
                        //examNode.className = "closed";
                        span = document.createElement("span");
                        span.className = "folder";
                        span.appendChild(createTextNode(aExam.Description));
                        examNode.appendChild(span);

                        var detailNode = document.createElement("ul");
                        var examTime = document.createElement("li");
                        span = document.createElement("span");
                        span.className = "file";
                        span.appendChild(createTextNode(aExam.ExamTime));
                        examTime.appendChild(span);
                        detailNode.appendChild(examTime);

                        var score = document.createElement("li");
                        span = document.createElement("span");
                        span.className = "file";
                        span.appendChild(createTextNode(aExam.Score));
                        score.appendChild(span);
                        detailNode.appendChild(score);

                        examNode.appendChild(detailNode);

                        examesNode.appendChild(examNode);
                    });

                    classNode.appendChild(examesNode)

                    classesNode.appendChild(classNode);
                });

                studentNode.appendChild(classesNode);
                root.appendChild(studentNode);
            });

            $("#StudentTree").html("").append(root);
            $("#StudentTreeRoot").treeview();
        };

        $(document).ready(function () {
            $("#StudentTree").html("");
            $.ajax({
                cache: false,
                type: "POST",
                async: false,
                url: GetStudentsURL
                    + "/?NoOfStudents=" + NoOfStudents
                    + "&NoOfClasses=" + NoOfClasses
                    + "&NoOfExams=" + NoOfExams,
                dataType: "json",
                success: function (students) {
                    StudentJson = FixDateinJson(students);
                    buildStudentTree(StudentJson);
                }
            });

            $("#btnAddAnExamJson").click(function () {
                $("#StudentTree").html("Loading ...");

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: AddAnExamByJsonURL,
                    contentType: 'application/json',
                    dataType: "json",
                    data: JSON.stringify(StudentJson),
                    success: function (students) {
                        StudentJson = FixDateinJson(students);
                        buildStudentTree(StudentJson);
                    }
                });
            });

            $("#btnAddAnExamSession").click(function () {
                $("#StudentTree").html("Loading ...");

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: AddAnExamBySessionURL,
                    dataType: "json",
                    success: function (students) {
                        StudentJson = FixDateinJson(students);
                        buildStudentTree(StudentJson);
                    }
                });
            });
        });
    </script>
</head>

<body>
    <div id="TitleContainer"><%= ViewData["ApplicationTitle"]%></div>
    <div id="MainContainer">
        <div id="StudentTree"></div>
        <div id="ButtonContainer">
            <button id="btnAddAnExamSession" class="ButtonStyle">
                Add an exam to students using session</button>
            <button id="btnAddAnExamJson" class="ButtonStyle">
                Add an exam to students by posting Json</button>
        </div>
    </div>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dr. Song Li

United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

| Advertise | Privacy | Mobile
Web04 | 2.8.140814.1 | Last Updated 24 Nov 2010
Article Copyright 2010 by Dr. Song Li
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid