本篇体验在ASP.NET MVC下使用Knockout,将使用EF Code First创建数据库。最后让Knockout绑定一个Json对象。
创建一个领域模型。
monospace; width: 100%; margin: 0em; background-color: #f0f0f0">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的同步