本篇体验在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的同步

在ASP.NET MVC中使用Knockout实践01,绑定Json对象的更多相关文章

  1. 在ASP.NET MVC中使用Knockout实践09,自定义绑定

    Knockout真正强大之处在于绑定机制,通过data-bind属性值体现绑定,不仅可以绑定值,还可以绑定事件,甚至可以自定义绑定. 从一个例子看Knockou的绑定机制 假设想给一个button元素 ...

  2. 在ASP.NET MVC中使用Knockout实践06,自定义验证、异步验证

    在上一篇中体验了Knockout.Validation的基本验证,本篇体验自定义验证和异步验证. 自定义验证规则 ko.validation有一个rules属性,专门用来存放验证规则,它是一个键值对集 ...

  3. 在ASP.NET MVC中使用Knockout实践02,组合View Model成员、Select绑定、通过构造器创建View Model,扩展View Model方法

    本篇体验使用ko.computed(fn)计算.组合View Model成员.Select元素的绑定.使用构造器创建View Model.通过View Model的原型(Prototype)为View ...

  4. 在ASP.NET MVC中使用Knockout实践07,自定义验证信息的位置与内容

    在前两篇中,体验了Knockout的基本验证和自定义验证.本篇自定义验证信息的显示位置与内容. 自定义验证信息的显示位置 通常,Knockout的验证信息紧跟在input后面,通过validation ...

  5. 在ASP.NET MVC中使用Knockout实践08,使用foreach绑定集合

    本篇体验使用 foreach 绑定一个Product集合. 首先使用构造创建一个View Model. var Product = function(data) { this.name = ko.ob ...

  6. 在ASP.NET MVC中使用Knockout实践05,基本验证

    本篇体验View Model验证.Knockout的subscribe方法能为View Model成员注册验证规则. @{ ViewBag.Title = "Index"; Lay ...

  7. 在ASP.NET MVC中使用Knockout实践04,控制View Model的json格式内容

    通常,需要把View Model转换成json格式传给服务端.但在很多情况下,View Model既会包含字段,还会包含方法,我们只希望把字段相关的键值对传给服务端. 先把上一篇的Product转换成 ...

  8. 在ASP.NET MVC中使用Knockout实践03,巧用data参数

    使用Knockout,当通过构造函数创建View Model的时候,构造函数的参数个数很可能是不确定的,于是就有了这样的一个解决方案:向构造函数传递一个object类型的参数data. <inp ...

  9. Asp.net MVC中文件上传的参数转对象的方法

    参照博友的.NET WebApi上传文件接口(带其他参数)实现文件上传并带参数,当需要多个参数时,不想每次都通过HttpContext.Request.Params去取值,就针对HttpRequest ...

随机推荐

  1. 高通Trustzone and QSEE介绍

    http://blog.csdn.net/iamliuyanlei/article/details/52625968

  2. dblinks

    一.Oracle数据库链Database links的作用 当用户要跨本地数据库,访问另外一个数据库表中的数据时,本地数据库中必须创建了远程数据库的dblink,通过dblink本地数据库可以像访问本 ...

  3. springboot日志框架

    Spring Boot日志框架Spring Boot支持Java Util Logging,Log4j2,Lockback作为日志框架,如果你使用starters启动器,Spring Boot将使用L ...

  4. 002_分布式搜索引擎Elasticsearch的查询与过滤

    一.写入 先来一个简单的官方例子,插入的参数为-XPUT,插入一条记录. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 curl -XPUT 'http:/ ...

  5. jquery-easyui:如何设置组件属性

    在这里以面板为例: $().ready(function() { $('#menu').tree({ url : '/menu', onClick : function(node) { $('#cen ...

  6. OS X 10.11:在exFAT分区的外置硬盘上使用Time Machine。

    Time Machine默认需要使用HFS+分区的外置硬盘,但在网络硬盘上也可以使用单个的 .sparsebundle 镜像文件备份.在本地USB或Firewire等接口连接的外置硬盘,只有exFAT ...

  7. 浅谈js设计模式 — 享元模式

    享元(flyweight)模式是一种用于性能优化的模式,“fly”在这里是苍蝇的意思,意为蝇量级.享元模式的核心是运用共享技术来有效支持大量细粒度的对象. 假设有个内衣工厂,目前的产品有 50种男式内 ...

  8. CentOS6安装Jenkins

    1.安装最新版JDK(作为JENKINS运行环境)# mount -t cifs //192.168.8.1/share /mnt -o username=share,password=share,n ...

  9. ClouderaManager中Event Server报No such file or directory

    错误日志如下: 2015-06-24 06:13:10,176 ERROR com.cloudera.cmf.eventcatcher.server.EventCatcherService: Erro ...

  10. grep 详解

    grep 是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来.(global search regular expression(RE) and print out the l ...