Breeze and knockout quick start.

An attempt at a bare minimum to get breeze and knockout going.


Create a new MVC4 web application web api project. This will bring in jQuery and knockout.
Nuget install-package Breeze.WebApi.
Add a dbcontext class in Models and a breeze api controller in Controllers.
Add an html page with a view model and a view.


using System.Linq;
using System.Web.Http;
using Breeze.WebApi;
using MvcApplication1.Models;
using Newtonsoft.Json.Linq;
namespace MvcApplication1.Controllers
{
[BreezeController]
public class FooController : ApiController
{
private readonly EFContextProvider<FooData> _ctx = new EFContextProvider<FooData>();
[HttpGet]
public string Metadata()
{
return _ctx.Metadata();
}
[HttpGet]
public IQueryable<Foo> Foos()
{
return _ctx.Context.Foo;
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _ctx.SaveChanges(saveBundle);
}
}
}


using System;
using System.Data.Entity;
namespace MvcApplication1.Models
{
public class Foo
{
public int Id { get; set; }
public String Name { get; set; }
}
public class FooData : DbContext
{
public DbSet<Foo> Foo { get; set; }
}
}

view raw

FooData.cs

hosted with ❤ by GitHub


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<title></title>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/knockout-2.2.0.js"></script>
<script src="Scripts/q.min.js"></script>
<script src="Scripts/breeze.min.js"></script>
<script type="text/javascript">
var mgr = new breeze.EntityManager("breeze/Foo");
var Vm = function () {
var items = ko.observableArray();
var item = ko.observable();
mgr.executeQuery(breeze.EntityQuery.from("Foos"))
.then(function (val) {
val.results.forEach(function (result) {
items.push(result);
});
});
function add() {
items.push(mgr.createEntity("Foo", { Name: item() }));
mgr.saveChanges();
item("");
}
function remove(data) {
data.entityAspect.setDeleted();
mgr.saveChanges();
items.remove(data);
}
return {
items: items,
item: item,
add: add,
remove: remove
};
};
$(function () {
ko.applyBindings(new Vm());
});
</script>
</head>
<body>
<form data-bind="submit: add">
<input type="text" data-bind="value: item" />
<input type="submit" value="add" />
</form>
<div data-bind="foreach: items">
<span data-bind="text: Name"></span>
<input type="button" value="delete" data-bind="click: $parent.remove" />
<br />
</div>
</body>
</html>

view raw

HtmlPage1.html

hosted with ❤ by GitHub



Leave a comment