I want to display my information from my classes to my view in mvc. I want to display information as JSON.
This is how my JSON needs to look like:
{ "timestamp": "2017-06-20 12:12:10", "categories": [ { "name": "Fiction", }, { "name": "Roman", } ] , "types": [ { "name": "Long story", }, { "name": "Short story", } ], "books": [ { "title": "Song of ice and fire", "bookNumber": "1234567", "aisle": [ { "location": "fiction isle", }, { "location": "roman aisle", } ] } ] } this is the classes i created
public class Category { public string name { get; set; } } public class Type { public string name { get; set; } } public class Aisle { public string location { get; set; } } public class Book { public string title { get; set; } public string bookNumber { get; set; } public List<Aisle> aisle { get; set; } } public class RootObject { public string timestamp { get; set; } public List<Category> categories { get; set; } public List<Type> types { get; set; } public List<Book> books { get; set; } } I'm pretty new to JSON and mvc, so im kinda stuck on how to proceed forward.
I created some constructors like this
public Book() { title = "Song of ice and fire"; bookNumber = "1234567" public List<Aisle> aisle { get; set; } } public Book(string _title, string _bookNum) { title = _title; bookNumber = _bookNum } my mvc
public ActionResult Testing() { ImportBooks m1 = new ImportBooks(); return Json(m1, JsonRequestBehavior.AllowGet); } and my view
@section Scripts{ <script type="text/javascript"> $("#btnGetBooks").click(function () { var actionUrl = '@Url.Action("Testing", "Books")'; $.getJSON(actionUrl, displayData); }); function displayData(response) { if (response != null) { for (var i = 0; i < response.length; i++) { $("#bookList").append(); } } } </script> } <h2>testing</h2> <input name="btnGetBooks" id="btnGetBooks" type="submit" value="Get Movies"> <p id="bookList"></p> I dont know whether constructors are the way to go, but i really do not know how to display data into my view.
Please help!
ImportBooks- but the json you have shown matchedRootObjectso if that is what you want to pass to the view, then itsRootObject model = new RootObject(); // set some properties return return Json(model , JsonRequestBehavior.AllowGet);RootObjectto the view, your loop makes no sense (its not a collection). And what is it you want to append to the<p id="bookList">element (some<span>elements containing the values of yourRootObject? You need to explain what the result you want is