本篇体验在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. linux系统基本排查

    1.查看内存使用情况 free -g 当观察到free栏已为0的时候,表示内存基本被吃完了,那就释放内存吧. 释放内存: sync echo 3 > /proc/sys/vm/drop_cach ...

  2. artDialog4.1.7 摘自网络

    jquery.artDialog.source.js学习 1 关键的对象关系 art = jQuery = $ function artDialog() {...} artDialog.fn = ar ...

  3. NEERC Southern Subregional 2011

    NEERC Southern Subregional 2011 A - Bonnie and Clyde solution 双指针搞搞就好. 时间复杂度:\(O(n)\) B - Building F ...

  4. VUE之搭建脚手架

    原文转自http://blog.csdn.net/Shiyaru1314/article/details/54963027 目录(?)[-] 1 安装之前需要检查是否已经安装NodeJS的环境 安装文 ...

  5. CSS------如何让div中的div处于右下角

    如图: 代码: <div style="width:300px;height:300px"> <div style="position:absolute ...

  6. 电脑同时安装Python2和Python3以及virtualenvwrapper(转)

    电脑同时安装Python2和Python3以及virtualenvwrapper  https://www.jianshu.com/p/d22f19496e03   windows: 1 下载地址:P ...

  7. 报错:-bash: locate: command not found

    -bash: locate: command not found 查看某些文件在哪些地方,需要用到 locate 命令 但是在安装 yum install locate 会报以下错误: -bash: ...

  8. sorted()排序详解

    sorted()排序详解     http://wiki.python.org/moin/HowTo/Sorting?highlight=%28howto%29#The_Old_Way_Using_t ...

  9. Noip2018游记——AFO

    本来Day 0和Day 1写得挺轻松的,结果没想到Day 2是这样的画风...心情逐渐沉重... Day 0 白天的时候颓的一批,上午考的信心赛还打错了一个字母然后$100pts\rightarrow ...

  10. python MySQL慢查询监控

    MySQL慢查询会话监控 #!/usr/bin/python # -*- coding: UTF-8 -*- from email.mime.text import MIMEText from ema ...