首页 > 代码库 > KnocoutJs+Mvc+BootStrap 学习笔记

KnocoutJs+Mvc+BootStrap 学习笔记

Mvc

  1.Html 增加扩展方法

技术分享
 1 using System.Web.Mvc;
 2 
 3 namespace KnockoutBootstrapMvc.Entensions
 4 {
 5     public static class HtmlHelperExtensions
 6     {
 7         public static HtmlString HtmlConvertToJson(this HtmlHelper htmlHelper, object model)
 8         {
 9             var setting = new JsonSerializerSettings
10             {
11                 ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
12                 Formatting = Formatting.Indented
13             };
14             return new HtmlString(JsonConvert.SerializeObject(model, setting));
15         }
16     }
17 }
View Code

 2.Code First

   创建Entity实体,当有外键关联时,可以在类内部创建virtual ObjClass  如果是数组为ICollection<ObjectClass>

技术分享
 1  public class Author
 2     {
 3         public int Id { get; set; }
 4         public string FirstName { get; set; }
 5         public string LastName { get; set; }
 6         public string Biography { get; set; }
 7         public virtual ICollection<Book> Books { get; set; }
 8     }
 9 
10    public class Book
11     {
12         public int Id { get; set; }
13         public string Title { get; set; }
14         public string Isbn { get; set; }
15         public string Synopsis { get; set; }
16         public string Description { get; set; }
17         public string ImageUrl { get; set; }
18         public virtual Author Author { get; set; }
19 
20     }
View Code


3.Db类库\重写OnModelCreating方法

   创建Db类继承DbContext,

 创建无参构造函数,设置父类连接字符串的名称

 创建实体对象  Public DbSet<EntityName> PropertyName {get;set;}

 重写OnModelCreating方法,此方法内在实体类创建时触发,可以设置实体的创建格式  如:开启、关闭默认的Id列为主键,是否自增标识列等。

技术分享
 1  public class BookContext:DbContext
 2     {
 3         public BookContext()
 4             :base("BookContext")
 5         {
 6 
 7         }
 8 
 9         public DbSet<Book> Books { get; set; }
10         public DbSet<Author> Authors { get; set; }
11 
12         protected override void OnModelCreating(DbModelBuilder modelBuilder)
13         {
14             modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
15             base.OnModelCreating(modelBuilder);
16         }
17 
18     }
View Code

 4.创建数据库启动程序类库,集成DropCreateDataBaseIfModelChanges<T> 、重写Seed方法用来初始化表格信息、向数据库表格中插入数据。

  未直接save的表,在save关联表时,数据也会插入进去

技术分享
 1 public class BookInitializer : DropCreateDatabaseIfModelChanges<BookContext>
 2     {
 3         protected override void Seed(BookContext context)
 4         {
 5             var author = new Author()
 6             {
 7                 Biography = "..",
 8                 FirstName = "zang",
 9                 LastName = "san"
10             };
11             var books = new List<Book>()
12             {
13                 new Book()
14                 {
15                        Author=author,
16                        Description="...",
17                        ImageUrl="http://ecx.images-amazon.com",
18                        Isbn="14919143",
19                        Title="Knokout.js",
20                         Synopsis="..."
21 
22                 },
23                 new Book()
24                 {
25                       Author=author,
26                        Description="...",
27                        ImageUrl="http://ecx.images-amazon.com",
28                        Isbn="14919142",
29                        Title="bootstrap.css",
30                         Synopsis="..."
31                 }
32                 ,
33                 new Book()
34                 {
35                       Author=author,
36                        Description="...",
37                        ImageUrl="http://ecx.images-amazon.com",
38                        Isbn="14919146",
39                        Title="asp.net mvc",
40                         Synopsis="..."
41                 }
42         };
43 
44             author = new Author()
45             {
46                 Biography = "..",
47                 FirstName = "li",
48                 LastName = "si"
49             };
50             books.Add(new Book()
51             {
52                 Author = author,
53                 Description = "...",
54                 ImageUrl = "http://ecx.images-amazon.com",
55                 Isbn = "14919146",
56                 Title = "lisi asp.net mvc",
57                 Synopsis = "..."
58             });
59 
60             books.ForEach(b => context.Books.Add(b));
61             context.SaveChanges();
62             //base.Seed(context);
63             
64             //new BookInitializer();
65         }
66 
67     }
View Code

    在应用启动方法中设置数据库对象,

  1.Global.asax中创建Db对象

  2.DataBase.SetInitialzer(new Objclass);

  3.Db对象.DataBase.Initialize(true);

 

技术分享
 1  1 namespace KnockoutBootstrapMvc
 2  2 {
 3  3     public class MvcApplication : System.Web.HttpApplication
 4  4     {
 5  5         protected void Application_Start()
 6  6         {
 7  7             AreaRegistration.RegisterAllAreas();
 8  8             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 9  9             RouteConfig.RegisterRoutes(RouteTable.Routes);
10 10             BundleConfig.RegisterBundles(BundleTable.Bundles);
11 11 
12 12             var bookContext = new BookContext();
13 13             Database.SetInitializer(new BookInitializer());
14 14             bookContext.Database.Initialize(true);
15 15 
16 16         }
17 17     }
18 18 }View Code
View Code

 

5.Controller 方法属性前可以使用HttpPost等定义访问请求格式及是否启用验证

技术分享
 1   // POST: Authors/Create
 2         // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 
 3         // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598
 4         [HttpPost]
 5         [ValidateAntiForgeryToken]
 6         public ActionResult Create([Bind(Include = "Id,FirstName,LastName,Biography")] Author author)
 7         {
 8             if (ModelState.IsValid)
 9             {
10                 db.Authors.Add(author);
11                 db.SaveChanges();
12                 return RedirectToAction("Index");
13             }
14 
15             return View(author);
16         }
View Code

 6.@sections 定义标签,在Layout页面里可以使用 @RenderSection(name:required:) 来加载对应的标签

 

PageA.cshtml
@section scripts
    {
      <script type="text/javascript">

          function ViewModel(authors)
          {
              var self = this;
              self.authors = authors;
          }

          var viewModel = new ViewModel(@Html.HtmlConvertToJson(Model));
          ko.applyBindings(viewModel);
      </script>
     
    }

Layout.cshtml
 @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <script type="text/javascript" src=http://www.mamicode.com/"~/Scripts/knockout-3.4.0.js"></script>
    @RenderSection( name:"scripts", required: false)
    

 

KnocoutJs+Mvc+BootStrap 学习笔记