twitter bootstrap - Binding a collection of blog items to view using Knockout JS in MVC 5 -
i have scenario of displaying collection of blog post in view asp.net mvc 5 application. not able iterate collection on view in order display list of blog post.
my code follows,
the model class
public class blogs { public int blogid { get; set; } public string blogname { get; set; } public string smalldescription { get; set; } public datetime creationdate { get; set; } public list<string> tags { get; set; } }
the collection class
public class blogcollection { public list<blogs> getlatestblogs() { var blogs = new list<blogs>(); var blog1 = new blogs { blogid = 1, blogname = "alice in wonderland, part dos", smalldescription = " ought ashamed of asking such simple question" + "added gryphon; , both sat silent , looked @ poor alice, felt ready sink earth. " + "at last gryphon said mock turtle, drive on, old fellow! don t day it! , went on in these words:" + "yes, went school in sea, though mayn t believe it— " + "i never said didn t! interrupted alice." + "you did, said mock turtle.", creationdate = datetime.now, tags = new list<string> { "wpf", "mvc", "mvvm" } }; var blog2 = new blogs { blogid = 5, blogname = "revolution has begun! ", smalldescription = " if using javascript post list of tags may more interested in tag manage api, see below how retrieve list of tags entered user using api or how have tag manager automatically push tags ajax location.", creationdate = datetime.now, tags = new list<string> { "sql", "ssis", "ssas" } }; blogs.add(blog1); blogs.add(blog2); return blogs; } }
}
the client side viewmodel javascript
blogviewmodel = function (data) { var self = this; ko.mapping.fromjs(data, {}, self); };
finally view want list posts,
@model ienumerable<testapplication.models.blogs> @using system.web.script.serialization; @{string data = new javascriptserializer().serialize(model);} @section scripts{ <script src="~/scripts/knockout-3.3.0.js"></script> <script src="~/scripts/knockout.mapping-latest.js"></script> <script src="~/scripts/blogviewmodel.js"></script> <script type="text/javascript"> var blogviewmodel = new blogviewmodel(@html.raw(data)); ko.applybindings(blogviewmodel); </script> } <div class="well well-sm"> <div class="tabbable-panel"> <div class="tabbable-line"> <ul class="nav nav-tabs"> <li class="active"> <a href="#tab_default_trends" data-toggle="tab"> trending! </a> </li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tab_default_trends"> <div class="container"> <div class="col-md-12" data-bind="foreach: blogviewmodel"> <h3> <a href="#" class="btn-link" data-bind="text: blogname"> </a> </h3> <p data-bind="text: smalldescription"> </p> <div> <span class="badge" data-bind="text: creationdate"></span> </div> </div> </div> </div> </div> </div> </div> </div>
this code runs fine without data.
Comments
Post a Comment