1

Hi guys I have the following JSON list

{
  "students": [{
    "Name" : "Robert Mcguffin",
    "Registered" : "2014-07-20 05:34:16",
    "Student No:" : 1
} , {
    "Name" : "Agathe Dubois",
    "Registered" : "2014-05-30 09:46:26",
    "Student No:" : 2
} , {
    "Name" : "Steven Corral",
    "Registered" : "2015-02-11 09:58:16",
    "Student No:" : 3
}]
}

I need to be able to publish the following data to a table in an mvc application.

First and foremost I've done my research and it said that I should use deserialization with json.net so it makes an object list with the information supplied. Then I should use a view to publish the list to html.

How do I do this and if I do it will I be able to search the list given above using a dropdown which specifies either Name, Registered or StudentNo and then displays the student that it searched for? I know how to implement the search using sql but not sure if I could search the list otherwise.

Code for my Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StudentApplication.Models
{
       public class Students
    {
        public string Name {get; set;}
        public DateTime Registered {get; set;}
        public int StudentNo {get; set;}
    }

    public class StudentList
    {
        public List<Students> students {get; set;}
    }
}

Code for my controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace StudentApplication.Controllers
{
    public class UserController : Controller
    {
        [HttpGet]
        public ActionResult List()
        {

            var resolveRequest = HttpContext.Request;
            List<Students> model = new List<Students>();
            resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
            if (jsonString != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                model = (List<Students>)serializer.Deserialize(jsonString, typeof(List<Students>);
            }
            return View();
        }
    }
}

I got that last bit of code from How to Send Json String to Controller in mvc4 and Deserialize json

7
  • 1
    Unfortunately this is a very broad question. What have you tried so far? Can you share your code? What are you specifically struggling with? You can definitely deserialize the list into an object array, but you can also populate your table using JavaScript Commented Jul 25, 2015 at 23:19
  • Which one is simpler? Commented Jul 25, 2015 at 23:59
  • It really depends on how comfortable you are with JS and what your view looks like (i.e. are you using a JS-based table or a built-in MVC table?) Commented Jul 26, 2015 at 0:57
  • There was no instruction stating that I could use a js based table. The instructions just said make the table using c#.net mvc. Which is the reason why I'm stuck. I'm trying to find the simplest method to doing it and I have no clue whether to use a js based table which I've seen looks a lot easier than deserialization. Maybe another clue to what I could use is that I need pagination and a search function using the names of the columns Commented Jul 26, 2015 at 0:58
  • If you need pagination and search I highly recommend using a JS-based library that implement those features for you. jqGrid is a jQuery-based tool that I have used before and supports both pagination and search functions. Commented Jul 26, 2015 at 1:22

1 Answer 1

2

The question can be answered in many ways. I agree in the recommendation for using some JavaScript library. This will prevent any unnecessary and extra traffic to the server. In this example you combine MVC.NET with Knockout to solve this issue. I have placed the code in same place to prevent complexities for this example.

Student Class:

public class Students
    {

        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Registered { get; set; }

    }

Your MVC Controller could look this: Notice that we load the JSON file and then we pass it using an AJAX call.

private static List<Students> GetStudents()
{
        //the json could come from a database or a file. I am just simplifying
        const string data = @"
            [
            {
                'Name': 'Robert Mcguffin',
                'Registered': '2014-07-20 05:34:16',
                'Id': 1
            },
            {
                'Name': 'Agathe Dubois',
                'Registered': '2014-05-30 09:46:26',
                'Id': 2
            },
            {
                'Name': 'Steven Corral',
                'Registered': '2015-02-11 09:58:16',
                'Id': 3
            }
        ]";

        var serializer = new JavaScriptSerializer();
        var students = (List<Students>) serializer.Deserialize(data,typeof(List<Students>));

        return students;
  }

    [HttpGet]
    public JsonResult GetStudentsJsonList()
    {
        var students = GetStudents();
        return Json(students, JsonRequestBehavior.AllowGet);
    }

Our View could use knockoutJS to create an efficient search for either the id or student name (you can expand that to more fields):

<!--Move these JS library from the view. I left them for demostration purposes only -->
<script>

    Array.prototype.unique = function () {
        var a = this.concat();
        for (var i = 0; i < a.length; ++i) {
            for (var j = i + 1; j < a.length; ++j) {
                if (a[i] === a[j])
                    a.splice(j--, 1);
            }
        }
        return a;
    };

    ko.observableArray.fn.contains = function (prop1, prop2, value) {
        if (value.length > 0) {
            var val = ko.utils.unwrapObservable(value).toUpperCase();

            var arr1 = ko.utils.arrayFilter(this(), function (item) {
                return ko.utils.unwrapObservable(item[prop1]) == val;
            });

            var arr2 = ko.utils.arrayFilter(this(), function (item) {
                return ko.utils.unwrapObservable(item[prop2]).toUpperCase().indexOf(val) > -1;
            });

            return arr1.concat(arr2).unique();

        } else {
            return this();
        }

    };

    var StudentsModel = function () {
        var self = this;
        self.TextToSearch = ko.observable('');
        self.StudentsList = ko.observableArray([]);
        self.StudentsFound = ko.computed(function () {
            return self.StudentsList().length;
        });
    }

    var vm = new StudentsModel();

    function LoadStudents() {
        $.ajax("GetStudentsJsonList",
        {
            type: "GET",
            dataType: "json",
            statusCode: {
                200: function (data) {
                    vm.StudentsList(data);
                }
            },
            error: function () {
                alert('Error loading Students Json file');
            }
        });
    }

    $(document).ready(function () {
        ko.applyBindings(vm);
        LoadStudents();
    });

</script>

<h4>Knockout Lab</h4>
<div class="col-md-12 panel-default">
    <input placeholder="Search by name, or id" class="form-control" data-bind="value: TextToSearch,valueUpdate:'afterkeydown'" />
</div>

<div class="col-md-12">
    <ul data-bind="foreach: StudentsList.contains('Id', 'Name', TextToSearch())" class="list-group">
        <li class="list-group-item">
            <span data-bind="text:Id"></span>
            <span data-bind="text:Name"></span>
        </li>
    </ul>

</div>

You can visit my site to see this working: http://www.portaldelgado.com/Students

Or from my Git

Sign up to request clarification or add additional context in comments.

10 Comments

I'm assuming that the students class is the whole of the model? And unfortunately your git is giving me a 404 error.
Here I am using the Student class in C# to tell me what to use in my Knockout Model. In this example I am just using an array (observable array) that holds the students but I could expand it as needed. I updated the GitHub link.
Thank you for updating the git but at the moment It's not loading the page. Could not load file or assembly 'System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Please try now, I think that I had some problems placing my urls here. Let me know if you have issues and whether on loading Github or my site
Sorry for being vague. I meant in Microsoft Visual Studio 2013 for web. When I press ctrl+f5 it gives me that error. I checked the folder structure and I can't find anything wrong with it. It does work on your site though
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.