本篇體驗在ASP.NET MVC下使用Knockout,將使用EF Code First建立資料庫。最後讓Knockout繫結一個Json物件。
建立一個領域模型。
namespace MvcApplication3.Models
{public class Product{public int Id { get; set; }public string Name { get; set; }public string Category { get; set; }public decimal Price { get; set; }}}
派生於DbContext的上下文。
using System.Data.Entity;
namespace MvcApplication3.Models
{public class ProductContext : DbContext{public ProductContext() : base("conn"){Database.SetInitializer(new ProductInitializer());
}public DbSet<Product> Products { get; set; }}}
設定一些種子資料。
using System.Data.Entity;
namespace MvcApplication3.Models
{public class ProductInitializer : DropCreateDatabaseIfModelChanges<ProductContext>{protected override void Seed(ProductContext context){context.Products.Add(new Product() {Name = "秋意真濃", Price = 85M, Category = "散文"});context.Products.Add(new Product() {Name = "冬日戀歌", Price = 95M, Category = "小說" });context.Products.Add(new Product() { Name = "春暖花開", Price = 105M, Category = "散文" });}}}
Web.config中connectionStrings節點配置。
<connectionStrings>...<add name="conn" connectionString="Data Source=.;User=使用者名稱;Password=密碼;Initial Catalog=ProductStore;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings>
建立一個針對Product領域模型的介面。
using System.Collections.Generic;
namespace MvcApplication3.Models
{public interface IProductRepository{IEnumerable<Product> GetAll();Product GetById(int id);
Product Add(Product item);bool Update(Product item);
bool Delete(int id);}}
對IProductRepository介面的實現。
using System.Data;
namespace MvcApplication3.Models
{public class ProductRepository : IProductRepository{private ProductContext db = new ProductContext();public System.Collections.Generic.IEnumerable<Product> GetAll()
{return db.Products;
}public Product GetById(int id){return db.Products.Find(id);
}public Product Add(Product item)
{db.Products.Add(item);db.SaveChanges();return item;
}public bool Update(Product item){db.Entry(item).State = EntityState.Modified;db.SaveChanges();return true;}public bool Delete(int id){Product product = db.Products.Find(id);db.Products.Remove(product);if (db.SaveChanges() > 0)
{return true;}else
{return false;}}}}
在HomeController中提供一個Action,用來獲取資料庫中第一條Product記錄,並以json格式返回。
using System;
using System.Web.Mvc;
using MvcApplication3.Models;
namespace MvcApplication3.Controllers
{public class HomeController : Controller{static readonly IProductRepository repository = new ProductRepository();public ActionResult Index()
{return View();
}public JsonResult GetFirstProduct()
{var product = repository.GetById(1);return Json(product, JsonRequestBehavior.AllowGet);
}}}
在Home/Index.cshtml中,讓Knockout繫結一個json型別的View Model,然後向控制器發出一個非同步請求,返回的資料更新json物件的name屬性。
@{ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}<div data-bind="text:name"></div> <hr/>
<input type="text" data-bind="value:name"/>@section scripts{<script src="~/Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript">
$(function() {ko.applyBindings(productViewModel);$.getJSON('@Url.Action("GetFirstProduct","Home")', function (data) {productViewModel.name(data.Name);});});var productViewModel = {id: ko.observable(""),name: ko.observable("初始值"),
price: ko.observable(""),category: ko.observable("")};</script>}
以上,
○ View Model的型別是一個json物件
○ 使用ko.observable(""),讓View Model的成員與介面保持同步
○ 介面檢視使用data-bind屬性實現與View Model的同步