Json object not rendering in MVC view - angularjs

I am having trouble passing JSON object to my view. I am using angular to later bind the data to my view. But when I execute the page, the table in blank. Please see the code below
Code in my view
<div class="container" ng-init="courses = #Html.Raw(Model)">
<div class="row">
<div class="span10">
<table class="table table-condensed table-hover">
<tr>
<th>Course</th>
<th>Course Name</th>
<th>Instructor</th>
</tr>
<tr ng-repeat="course in courses">
<td>{{course.number}}</td>
<td>{{course.name}}</td>
<td>{{course.instructor}}</td>
</tr>
</table>
</div>
</div>
</div>
Code in my controller
public class CoursesController : Controller
{
// GET: Hello
public ActionResult Index()
{
return View("Index", "", GetSerialisedCourseVm());
}
public string GetSerialisedCourseVm()
{
var courses = new[]
{
new CourseVM {Number= "100", Name= "Physis", Instructor = "Abc"},
new CourseVM {Number= "101", Name= "Chemistry", Instructor = "test"},
new CourseVM {Number= "102", Name= "Biology", Instructor = "Mac"},
new CourseVM {Number= "103", Name= "History", Instructor = "Jack"},
new CourseVM {Number= "104", Name= "Maths", Instructor = "Ren"}
};
var settings = new JsonSerializerSettings{ContractResolver = new CamelCasePropertyNamesContractResolver()};
return JsonConvert.SerializeObject(courses, settings);
}
}
public class CourseVM
{
public string Number { get; set; }
public string Name { get; set; }
public string Instructor { get; set; }
}
when i do an F12 i can see the following error
angular.min.js:62 Error: Unexpected end of expression: courses = [{
at Error (native)
at g (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:67:426)
at J (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:71:164)
at A (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:70:288)
at m (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:70:204)
at x (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:70:70)
at t (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:69:454)
at s (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:69:384)
at p (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:69:321)
at o (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js:69:251) <div class="container" ng-init="courses = [{" number":"100","name":"physis","instructor":"Abc"},{"number":"101","name":"chemistry","instructor":"test"},{"number":"102","name":"biology","instructor":"Mac"},{"number":"103","name":"history","instructor":"Jack"},{"number":"104","name":"maths","instructor":"Ren"}]"="">
Using the unminified version of angular
angular.js:13294 Error: [$parse:ueoe] Unexpected end of expression: courses = [{
http://errors.angularjs.org/1.5.2/$parse/ueoe?p0=courses%20%3D%20%5B%7B
at http://localhost:81/Scripts/angular.js:68:12
at Object.AST.peekToken (http://localhost:81/Scripts/angular.js:13895:13)
at Object.AST.object (http://localhost:81/Scripts/angular.js:13851:14)
at Object.AST.primary (http://localhost:81/Scripts/angular.js:13769:22)
at Object.AST.unary (http://localhost:81/Scripts/angular.js:13757:19)
at Object.AST.multiplicative (http://localhost:81/Scripts/angular.js:13744:21)
at Object.AST.additive (http://localhost:81/Scripts/angular.js:13735:21)
at Object.AST.relational (http://localhost:81/Scripts/angular.js:13726:21)
at Object.AST.equality (http://localhost:81/Scripts/angular.js:13717:21)
at Object.AST.logicalAND (http://localhost:81/Scripts/angular.js:13709:21) <div class="container" ng-init="courses = [{" number":"100","name":"physis","instructor":"Abc"},{"number":"101","name":"chemistry","instructor":"test"},{"number":"102","name":"biology","instructor":"Mac"},{"number":"103","name":"history","instructor":"Jack"},{"number":"104","name":"maths","instructor":"Ren"}]"="">
Output of #Html.Raw(Model) in the view
[{"number":"100","name":"Physis","instructor":"Abc"},{"number":"101","name":"Chemistry","instructor":"test"},{"number":"102","name":"Biology","instructor":"Mac"},{"number":"103","name":"History","instructor":"Jack"},{"number":"104","name":"Maths","instructor":"Ren"}]

The solution is simply to replace all the " marks with ' marks.
In your output for model, you have this:
[{"number":"100","name":"Physis","instructor":"Abc"},{"number":"101","name":"Chemistry","instructor":"test"},{"number":"102","name":"Biology","instructor":"Mac"},{"number":"103","name":"History","instructor":"Jack"},{"number":"104","name":"Maths","instructor":"Ren"}]
The " marks there are ending the ng-init attribute, causing it to only see ng-init="courses = [{".

Data Flow
Factory
set up a factory to get your data (where data is your JSON array)
.factory('homeFactory', [ function(){
return{
getData: function(){
return data
}
};
}]);
Controller
then in your controller you must use your factory
.controller('homeCtrl', [ '$scope','homeFactory', function($scope, homeFactory){
$scope.data = {};
homeFactory.getData().then(function(res){
$scope.data= res.data;
});
}]);
View
then in your view
just throw the curly bracket notation in a for each (this assumes that name is a json key in your array) or you can just print out data
<div ng-repeat="value in data">
{{value.name}}
</div>
please ask if there is something unclear and I will update this answer.

Related

Not able to display the value from Json response

I am trying to get a json web response from jersey web service using hibernate.The values are returned from database as i checked in the console.The problem is that when i try to print that in the angular like this
<h1>Welcome to Hibernate Jersey Angular CMS</h1>
<div id='err'></div>
<a href="add.html" class='btn btn-success'>New Article</a>
<p>
<div>
<table id='blogList' class="table table-bordered" ng-controller='MyController'>
<tr>
<th>Latest Articles</th>
<th>Actions</th>
</tr>
<tr ng-repeat='elem in data'>
<td>{{elem.id}}</td>
<td><a class='btn btn-warning' href="modify.html?id={{elem.id}}">Modify</a></td>
</tr>
</table>
</div>
</body>
<script src='javascripts/jquery2.1.3/jquery.min.js'></script>
<script src='javascripts/bootstrap3.3.2/js/bootstrap.min.js'></script>
<script src='javascripts/angular1.2.19/angular.js'></script>
<script src='javascripts/json/json2.js'></script>
<script>
function MyController($scope, $http) {
//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];
$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
}
</script>
</html>
the value is not displayed.It is displayed blank like this
I know i am getting proper response as the number of rows min the image is same as the number of entries in the table.This is my code for hibernate
public List<Love> getAllLeaves() {
Session session = HibernateTest.getSession();
String hql = "from Love";
Query qry = session.createQuery(hql);
List<Love> list = qry.list();
Iterator i=list.iterator();
while(i.hasNext())
{
Love l=(Love) i.next();
//System.out.println("staretd");
}
session.close();
return list;
}
and the jersey code
#GET
#Path("list")
#Produces({ "application/json" })
public List<Love> list() {
List l= new LeaveDao().getAllLeaves();
Iterator i=l.iterator();
while(i.hasNext())
{
Love m=(Love)i.next();
System.out.println(m.getLove());
}
return l;
}
and bean class
package com.king.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.ws.rs.QueryParam;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
public class Love {
public Love(String Love) {
this.id = Love;
}
public Love()
{}
public String getLove() {
return id;
}
public void setLove(String Love) {
this.id = Love;
}
#Id
#QueryParam("id")
private String id;
}
added network response

Angular/MVC Duplicates In Repeater Are Not Allowed

First, here is all the code that leads me to the error I'm getting:
The JSON:
[
{
"Id": 0,
"UserName": "uniqueusername",
"Photo": "base64string",
"Email": "user#user.com",
"Office": "Location "
},
{
"Id": 1,
"UserName": "uniqueusername",
"Photo": "base64string",
"Email": "user#user.com",
"Office": "Location"
},
{
"Id": 2,
"UserName": "uniqueusername",
"Photo": "base64string",
"Email": "user#user.com",
"Office": "Location"
},
{
"Id": 3,
"UserName": "uniqueusername",
"Photo": "base64string",
"Email": "user#user.com",
"Office": "Location"
},
{
"Id": 4,
"UserName": "uniqueusername",
"Photo": "base64string",
"Email": "user#user.com",
"Office": "Location"
}
]
It is generated using this function in my controller:
List<string> Names = arepo.GetAllAvionteUsers();
List<UserPreviewViewModel> AllUsers = new List<UserPreviewViewModel>();
int count = 0;
foreach(string name in Names)
{
UserPreviewViewModel preview = new UserPreviewViewModel(name);
preview.Id = count;
AllUsers.Add(preview);
count++;
if (count == 10) break;
}
return Json(new { Users = JsonConvert.SerializeObject(AllUsers, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore}) }, JsonRequestBehavior.AllowGet);
The View Model:
public int Id { get; set; }
public string UserName { get; set; }
public string Photo { get; set; }
public string Email { get; set; }
public string Office { get; set; }
the angular controller:
angular.module('app.module')
.factory('Users', ['$http', function UsersFactory($http) {
return {
AllUsers: function () {
return $http({ method: 'GET', url: '/Controller/GetAllUsers' });
}
}
}]);
angular.module('app.module')
.controller('UserController', ['$scope', 'Users', function ($scope, Users) {
var vm = this;
Users.AllUsers().success(function (data) {
vm.users = JSON.stringify(data.Users);
});
}]);
And finally the view:
<table class="dataTable row-border hover" datatable="ng" dt-instance="vm.dtInstance"
dt-options="vm.dtOptions">
<thead>
<tr>
<th class="secondary-text">
<div class="table-header">
<span class="column-title">Id</span>
</div>
</th>
<th class="secondary-text">
<div class="table-header">
<span class="column-title">Name</span>
</div>
</th>
<th class="secondary-text">
<div class="table-header">
<span class="column-title">Photo</span>
</div>
</th>
<th class="secondary-text">
<div class="table-header">
<span class="column-title">Email</span>
</div>
</th>
<th class="secondary-text">
<div class="table-header">
<span class="column-title">Office</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in vm.users">
<td>{{user.Id}}</td>
<td>{{user.UserName}}</td>
<td><img class="product-image" ng-src="data:img/jpg;base64,{{user.Photo}}"></td>
<td>{{user.EmailAddress}}</td>
<td>{{user.Office}}</td>
</tr>
</tbody>
</table>
Every time that I try to run this code I get the following error from my JSON:
angular.js:13920 Error: [ngRepeat:dupes] Duplicates in a repeater are
not allowed. Use 'track by' expression to specify unique keys.
Repeater: user in vm.users, Duplicate key: string:\, Duplicate value:
\
I have tried to use angular's suggested fix, which is track by $index and all that does is cause my page to freeze.
I have tried to take out the Formatting.Indented when I return the JSON string and all that does is give me the same error as well as taking out the ReferenceLoopHandling part and also getting the same error.
In the angular controller I tried to do JSON.parse(data) and I get the following error:
angular.js:13920 SyntaxError: Unexpected token o in JSON at position 1
When I try to do let users = data.Users and then do let count = users.length it gives me the number 85941 which seems like it is counting every single character in the string.
When I do a console.log(data) it gives me the JSON that I pasted above (I did change usernames, emails, and locations to keep my user's info safe).
At this point I have absolutely no clue what is wrong here or how to fix it, any help would be greatly appreciated.
Thanks!
Although I am not entirely sure as to why this error occurred in first place, the fix for it was not to return JSON from the controller. I modified my return statement like so:
return Json(JsonConvert.SerializeObject(AllUsers, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore}), JsonRequestBehavior.AllowGet);
Then in the angular controller i did:
vm.users = JSON.parse(data);
That gave me the proper JSON array and now it works perfectly.

How to send list inside model - AngularJS

i have a problem with my model.
I need send a list of another object to my controller, but i dont know how to create this object using AngularJS.
I have three input field, homePhone, cellphone and contact, all fields are about phone, and my ClientModel has a list of phones. What i want to do, is get this three fields and include in a list inside client model.
**MVC Model "Client"**
public int Id { get; set; }
public string Name { get; set; }
public string Email{ get; set; }
public IEnumerable<Phone> Phones { get; set; }
**MVC Model "Phone"**
public int PhoneId { get; set; }
public int ClientId { get; set; }
public int PhoneType { get; set; }
public string Number { get; set; }
View
<div class="form-group col-lg-4">
<label>Home Phone</label>
<input class="form-control" ng-model="?">
</div>
<div class="form-group col-lg-4">
<label>Cellphone</label>
<input class="form-control" ng-model="?">
</div>
<div class="form-group col-lg-4">
<label>Contact Phone</label>
<input class="form-control" ng-model="?">
</div>
<button class="btn btn-primary" style="float: right" ng-click="saveClient(client)">Confirmar</button>
Controller JS
$scope.saveClient = function(client) {
clientesAPI.saveCliente(client).success(function() {
alert('OK');
}).error(function () {
alert('Error');
});`enter code here`
}
What you could do is create actual Constructor functions in JS and consistently model you current Server Side MVC Model.
So is would look something like this ...
angular.module('app', [])
.factory('Client', function() {
return Client;
function Client() {
this.id = 0;
this.name = '';
this.email = '';
this.phones = [];
}
Client.prototype.init = function(client) {
this.id = client.id;
this.name = client.name;
this.email = client.email;
this.phones = [];
}
})
.factory('Phone', function() {
return Phone;
function Phone() {
this.phoneId = 0;
this.clientId = 0;
this.phoneType = 'Default Phone Type';
this.number = 0;
}
Phone.prototype.init = function(phone) {
this.phoneId = phone.phoneId;
this.clientId = phone.clientId;
this.phoneType = phone.phoneType;
this.number = phone.number;
}
})
.factory('clientService', function($http, $log, Client, Phone) {
var service = {
getClient: getClient,
saveClient: saveClient
};
return service;
//////////////////////////
function getClient() {
return $http.get('clientApi')
.then(success)
.catch(error)
// This is where defining actual JS Quote unQuote Classes comes in handy
function success(response) {
var clients = response.data;
angular.forEach(clients, function(client) {
client = new Client().init(client);
angular.forEach(client.phones, function(phone) {
phone = new Phone().init(phone);
})
})
return clients;
}
function error(response) {
$log.error('Error getting Clients: ' + response.data);
}
}
function saveClient(client) {
return $http.post('clientApi', client)
.then(success)
.catch(error)
// This is where defining actual JS Quote unQuote Classes comes in handy
function success(response) {
$log('Saved Client Successfully');
}
function error(response) {
$log.error('Error saving Client: ' + response.data);
}
}
})
// I would use Controller As Syntax normally
.controller('clientController', function($scope, clientService, Client, Phone) {
$scope.client = new Client();
$scope.client.phones.push(new Phone());
$scope.savedClient;
$scope.saveClient = function() {
$scope.savedClient = $scope.client;
alert('Yeah we saved some data!!');
//Unconmment this to access the real service, Nowhere to call here :-)
//clientService.saveClient($scope.client);
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="clientController">
<!-- Use ngRepeat to simplify things a bit -->
<div class="form-group col-lg-4" ng-repeat="phone in client.phones track by phone.phoneId">
<label>{{phone.phoneType}}</label>
<input class="form-control" ng-model="phone.number">
</div>
<!-- You will already have access to the updated model in you controller -->
<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmation</button>
<!--Display Saved Data-->
<pre>{{savedClient | json}}</pre>
</div>
</div>
I like the idea of this approach for a couple of reasons.
You can new up a Client or a Phone in you controller and know for a fact that or expected model properties are there when Angular tries to render them. (This avoids the annoying client.phones.phoneId is not defined errors)
Your model definition is now in one spot on the JS side of the house. Even though this looks like duplication ... well it is, but you will have to define this somewhere to send it back to the server anyways. So I prefer to do it in one reusable spot.
You get and Arrays of Client and Phone when you are outputting the model properties to the Console. This just make me feel good :-)
This was a bit of an overkill for your question, but I like the clean feel of this approach to Front End Modeling.
You can create a new object for your model and add the phones property there.
View
<div class="form-group col-lg-4">
<label>Home Phone</label>
<input class="form-control" ng-model="homePhone">
</div>
<div class="form-group col-lg-4">
<label>Cellphone</label>
<input class="form-control" ng-model="cellPhone">
</div>
<div class="form-group col-lg-4">
<label>Contact Phone</label>
<input class="form-control" ng-model="contactPhone">
</div>
<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmar</button>
Controller
$scope.saveClient = function() {
var phones = [
{ClientId: $scope.client.Id, PhoneType: 1, Number: $scope.homePhone},
{ClientId: $scope.client.Id, PhoneType: 2, Number: $scope.cellPhone},
{ClientId: $scope.client.Id, PhoneType: 3, Number: $scope.contactPhone}
]; // Not sure about the PhoneTypes. There are multiple ways to implement this, I'll leave it up to you.
var data = {
Id: $scope.client.Id,
Name: $scope.client.Name,
Email: $scope.client.Email,
Phones: phones
};
clientesAPI.saveCliente(data).success(function() {
alert('OK');
}).error(function () {
alert('Error');
});
};
first you need to define ng-model for your view, suppose -
<input class="form-control" ng-model="hPhone">
<input class="form-control" ng-model="cellPhone">
<input class="form-control" ng-model="contactPhone">
Now you can make a json object and post that, then on server side you can access all the phones by for-each loop -inside your controller -
var vm = this;
var phnList = {
hphone: vm.hphone,
cellPhone: vm.cellPhone,
contactPhn: vm.contactPhone
};
Now u can post using $http service
$(http).({
url : "urULR",
data : phnList,
method :"post"
}).then(fuction(response) {
vm.message = "save success";
});

Pushing multiple entries and saving them in database through AngularJS

I am stuck saving multiple rows I pushed in "$scope.arr" to my SQL Server database. I have my code below and it works fine but when I click on "Save To DB" button after adding/pushing some entries by pressing "Add Person" button, it passes a row with null values to SQL Server database. Please guide me where I am doing the mistake:
I also heard about using angular.forEach loop but I am confused using that too.
I have my model class "TestModel.cs" here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProj.Models
{
public class TestModel
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
My MVC Controller named TestController's Add method here:
[HttpPost]
public string AddPerson(TestModel test)
using (TestContext db = new TestContext())
{
if (test != null)
{
db.TestModels.Add(test);
db.SaveChanges();
return "Successful";
}
else
{
return "Failed";
}
}
}
My AngularJS script here:
var app = angular.module("TestApp", []);
app.controller("TestCtrl", function ($scope, TestService) {
$scope.arr = [];
$scope.addPerson = function () {
var myobj = {
FirstName: $scope.firstname,
LastName: $scope.lastname
}
$scope.arr.push(myobj);
};
$scope.savePerson = function () {
var TestData = TestService.AddPer($scope.arr);
TestData.then(function (msg) {
alert(msg.data);
}, function () {
alert('Error In Adding Person');
});
};
});
app.service("TestService", function ($http) {
this.AddPer = function (person) {
var response = $http({
method: "post",
url: "/Test/AddPerson",
data: JSON.stringify(person),
dataType: "json",
});
console.log(response);
return response;
}
});
And my Index.cshtml file here:
<div ng-controller="TestCtrl">
<form>
FirstName: <input class="form-control" ng-model="firstname" /><br />
LastName: <input class="form-control" ng-model="lastname" /><br />
<button class="btn btn-success" ng-click="addPerson()">Add Person</button>
<button class="btn btn-success" ng-click="savePerson()">Save To DB</button>
<table class="table table-bordered">
<tr>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="a in arr">
<td>{{$index+1}}</td>
<td>{{a.FirstName}}</td>
<td>{{a.LastName}}</td>
</tr>
</table>
</form>
</div>
<script src="~/Scripts/MyAngular/Module.js"></script>
Your help will be appreciated. Thanks!
Then server side action should expect collection of TestModel, you could us List there. If you [FromBody] before parameter, you don't need to stringify data before posting it to server.
Code
[HttpPost]
public string AddPerson([FromBody] List<TestModel> test)
using(TestContext db = new TestContext()) {
test.forEach(t=> {
if (t != null) {
db.TestModels.Add(t);
return "Successful";
} else {
return "Failed";
}
});
db.SaveChanges(); //save context at the end, when no error occurs
}
}
The problem was in my Server Side Code i.e, my C# controller, this method worked:
[HttpPost]
public void AddPerson(List<TestModel> test)
{
using (TestContext db = new TestContext())
{
foreach(var t in test)
{
if (t != null)
{
db.TestModels.Add(t);
Console.WriteLine("Success");
}
}
db.SaveChanges(); //save context at the end, when no error occurs
}
}

The simplest example of Knockback js working with a RESTful webservice such as ServiceStack?

I am looking for a VERY simple example that shows wiring up Knockback code to a backbone model that connects via RESTful service. I am using ServiceStack|c# backend. All of the links below are too complicated and use localStore rather than a RESTful service via url. I also prefer to see examples in Javascript not CoffeeScript.
My example url is something like localhost/entities where hitting this will cause the RESTful webservice to return all of the entities. Hitting it with localhost/entity/1 would return the entity with an Id of 1.
_http://kmalakoff.github.com/knockback/index.html
_https://github.com/kmalakoff/knockback-reference-app/
_https://github.com/addyosmani/todomvc
The following is the example from knockback tutorial on the first link:
Models, Collection, ViewModel, and Bindings:
// Generated by CoffeeScript 1.3.3
var model, view_model;
model = new Backbone.Model({
first_name: "Planet",
last_name: "Earth"
});
view_model = kb.viewModel(model);
view_model.full_name = ko.computed((function() {
return "" + (this.first_name()) + " " + (this.last_name());
}), view_model);
ko.applyBindings(view_model, $('#kb_view_model_computed')[0]);
But there is no mention of how you would wire the backbone model up to your RESTful webservice.
There are examples of how do this via Backbone but I am uncertain as to how things change when using Knockback.
The following links were found, but not helpful:
_http://stackoverflow.com/questions/7992431/using-knockoutjs-backbone-together
_http://stackoverflow.com/questions/9704220/is-knockback-js-production-ready
_http://stackoverflow.com/questions/10434203/defining-models-on-server-side-when-using-mvvm-with-knockout-js
Thanks in advance for any assistance provided. Btw you don't want hyperlinks you get underscores... ;)
With much help and support from Kevin Malakoff from the great Knockback project I was able to get a small example working! I used the ServiceStack Backbone Todos project as a starting point.
c# file: Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using ServiceStack.Redis;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
namespace MyApp
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonService : RestServiceBase<Person>
{
public static Person kevin = new Person { Id = 1, FirstName = "Kevin", LastName = "Malakoff" };
public static Person scott = new Person { Id = 2, FirstName = "Scott", LastName = "Idler" };
public static List<Person> people = new List<Person> { kevin, scott };
public override object OnGet(Person person)
{
if (person.Id != default(int))
return people[person.Id-1];
return people;
}
public override object OnPost(Person person)
{
return base.OnPost(person);
}
public override object OnPut(Person person)
{
return OnPost(person);
}
public override object OnDelete(Person person)
{
return base.OnDelete(person);
}
}
public class AppHost : AppHostBase
{
public AppHost() : base("MyApp", typeof(PersonService).Assembly) { }
public override void Configure(Funq.Container container)
{
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
Routes
.Add<Person>("/persons")
.Add<Person>("/persons/{Id}");
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
new AppHost().Init();
}
}
}
html file: default.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MyApp2</title>
<script>window.JSON || document.write('<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">\x3C/script>')</script>
<script src="Scripts/jquery-1.8.0.js" type="text/javascript" ></script>
<script src="Scripts/knockback-full-stack-0.16.1.js" type="text/javascript" ></script>
<script src="myapp.js" type="text/javascript" ></script>
</head>
<body>
<div id="myapp">
<div class="title">
<h1>MyApp</h1>
</div>
<div class="content">
<div id='kb_observable'>
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
<p>Hello, <span data-bind="text: fullName"></span>!</p>
</div>
<div id="kb_collection_observable">
<div data-bind="if: persons">
<span>Has Persons</span>
</div>
<div data-bind="foreach: persons">
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
</div>
</div>
</div>
</div>
</body>
</html>
javascript file: myapp.js
$(function() {
//model
var PersonModel = Backbone.Model.extend({ urlRoot: '/MyApp/persons' });
var model = new PersonModel({ id: 1 });
model.fetch();
//viewmodel
var PersonViewModel = function (person) {
this.firstName = kb.observable(person, 'firstName');
this.lastName = kb.observable(person, 'lastName');
this.fullName = ko.computed((function () {
return "" + (this.firstName()) + " " + (this.lastName());
}), this);
};
var personViewModel = new PersonViewModel(model);
//binding
ko.applyBindings(personViewModel, $('#kb_observable')[0]);
//model
var PersonsModel = Backbone.Collection.extend({ model: PersonModel, url: '/MyApp/persons' });
var personsModel = new PersonsModel();
personsModel.fetch();
//viewmodel
var PersonsViewModel = function (persons) {
this.persons = kb.collectionObservable(persons)
};
var personsViewModel = new PersonsViewModel(personsModel);
//binding
ko.applyBindings(personsViewModel, $('#kb_collection_observable')[0]); });
I put together a very simple example. It assumes you already know how to use backbone and knockout so this just gives a quick example of how they can be used together
http://coder2.blogspot.com/2013/02/backbonejs-and-knockoutjs.html

Resources