Reputation: 105
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
Upvotes: 0
Views: 2259
Reputation: 34
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
Upvotes: 1