Bootstraptable+knockoutjs implementation of adding and deleting solutions
Preface: The previous article introduced the lower KO to change the package, did save a lot of JS code. Bo is a lazy person, always feel that the basis of the effects of adding and deleting the results can be directly generated by a tool, what the code is not written, it is more cool. So the study of the next T4 grammar, although not fully mastered, but it is a general understanding. So here's the article today: quickly generate pages from T4 templates.
Knockoutjs Series Articles:
- JS Component Series--bootstraptable+knockoutjs Implement add and delete solution (i)
- JS Component Series--bootstraptable+knockoutjs Implementation of ADD and delete solutions (ii)
- JS Component Series--bootstraptable+knockoutjs Implementation of ADD and delete solutions (iii): Two ViewModel to fix additions and deletions
- JS Component Series--bootstraptable+knockoutjs Implement add and delete solution (iv): Customize T4 Template Quick Build page
Original address of this article: http://www.cnblogs.com/landeanfen/p/5667022.html
I. Introduction to the use of T4
We know that MVC in the addition of the view can be automatically generated add and delete changes to the page effect, that is because MVC for our built-in base additions and deletions to change the template, the syntax of these templates is to use T4, then where are these templates? Find the relevant article, found that MVC4 and the following version of the template location and MVC5 and the location of the above template is very different.
- MVC4 and the following versions of the template location: vs installation directory +\ITEMTEMPLATES\CSHARP\WEB\MVC 2\codetemplates. such as the blogger's D:\Program Files (x86) \microsoft Visual Studio 12.0\common7\ide\itemtemplates\csharp\web\ MVC 4\codetemplates. Find cshtml corresponding template, there are corresponding additions and deletions to change the TT file
- MVC5 and above template location: Give the blogger's template location directly D:\Program Files (x86) \microsoft Visual Studio 12.0\common7\ide\extensions\microsoft\web\ Mvc\scaffolding\templates
Knowing this, then the next step is to transform the template to add your own generated content. Can directly copy the list and edit template to come over to self-modification, but finally think about, or do not move the MVC built-in things, we own to build their own template is not better.
Create a new folder under the root of the current Web project, name Codetemplates, and then copy the Mvccontrollerempty and Mvcview two template folders inside the MVC template to the Codetemplates folder. Remove the original template from it, and then create a few of your own templates, such as:
This allows us to see our custom templates when adding new controllers and new views:
Second, T4 code introduction
The above describes how to create their own template, the template is built to start to plug the corresponding content, if the T4 of the grammar began to say that an article is not finished, interested in the garden can go to the garden to find, the article is quite a lot. Here's a look at a few template content. also need to explain, seemingly from MVC5, T4 template file suffix all changed to T4, and the previous template has been TT end, there is no scrutiny their grammatical differences, estimates should not be very different .
1, CONTROLLER.CS.T4
Why rewrite this empty controller template? Bo Master think adding and removing changes to find a lot of methods need to manually write trouble, write a template directly generated can save a lot. Take a look at the implementation code inside the template:
<#@ template language= "C #" hostspecific= "True" #><#@ output extension= "cs" #><#@ parameter type= " System.String "Name=" controllername "#><#@ parameter type=" System.String "name=" Controllerrootname "#><# @ parameter type= "System.String" name= "Namespace" #><#@ parameter type= "System.String" name= "AreaName" #>< # var index = controllername.lastindexof ("Controller"); var modelname = controllername.substring (0, index); #>using system;using system.collections.generic;using System.linq;using system.web;using system.web.mvc;using testko.models;namespace <#= namespace #>{public class &L t;#= controllername #>: Controller {public ActionResult Index () {return View (); } public ActionResult Edit (<#= modelname #> model) {return View (model); } [HttpGet] public jsonresult Get (int limit, int offset) {return Json (new {}, Jsonreques TbehavioR.allowget); }//New entity [HttpPost] public jsonresult Add (<#= modelname #> oData) {<#= Mo Delname #>model.add (OData); Return Json (New {}, Jsonrequestbehavior.allowget); }//Update entity [HttpPost] public jsonresult update (<#= modelname #> oData) {<#= ModelName #>model.update (OData); Return Json (New {}, Jsonrequestbehavior.allowget); }//delete entity [HttpPost] public jsonresult Delete (list<<#= modelname #>> oData) { <#= modelname #>model.delete (oData); Return Json (New {}, Jsonrequestbehavior.allowget); } }}
This content is not difficult to understand, directly view the generated controller code:
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using Testko.models;namespace testko.controllers{public class Usercontroller:controller {public ActionResult in Dex () {return View (); } public ActionResult Edit (User model) {return View (model); } [HttpGet] public jsonresult Get (int limit, int offset) {return Json (new {}, Jsonreques Tbehavior.allowget); }//New entity [HttpPost] public jsonresult Add (User oData) {usermodel.add (oData); Return Json (New {}, Jsonrequestbehavior.allowget); }//Update entity [HttpPost] public jsonresult update (User oData) {usermodel.update (oData); Return Json (New {}, Jsonrequestbehavior.allowget); }//delete entity [HttpPost] public jsonresult Delete (list<user> oData) { Usermodel.delete (OData); Return Json (New {}, Jsonrequestbehavior.allowget); } }}2, KoIndex.cs.t4
This template is mainly used to generate the list page, the approximate code is as follows:
<#@ template language= "C #" hostspecific= "True" #><#@ output extension= ". cshtml" #><#@ include file= " Imports.include.t4 "#><#//The following chained if-statement outputs the file header code and markup for a partial View, a view using a layout page, or a regular view.if (Ispartialview) {#><#} else if (islayoutpageselected) {#>@{ Viewbag.title = "<#= viewname#>";< #if (! String.IsNullOrEmpty (layoutpagefile)) {#> Layout = "<#= layoutpagefile#>"; <#}#>}<#} else {#>@{ Layout = null;} <! DOCTYPE html>Add a view index, and select the template
Get the page content
index.cshtmlWe moved the ViewModel on to the page, so that we didn't have to pass it through the controller every time. Change the column name of the table a little bit, and the page will run.
Here are some things to optimize:
(1) The query condition is not generated, if the syntax of T4 is a bit deeper, you can add attributes above the fields that need to be queried to identify which fields need to be queried and then automatically generate the corresponding query criteria.
(2) The column name of the table may also be generated by the property's field attribute. This is similar to the 1th, which requires studying the grammar of T4.
3, KOEDIT.CS.T4The third template page is the edited template, and its approximate code is as follows:
<#@ template language= "C #" hostspecific= "True" #><#@ output extension= ". cshtml" #><#@ include file= " Imports.include.t4 "#> @model <#= viewdatatypename #><#//" Form-control "attribute is only supported for all ED Itorfor () in SYSTEM.WEB.MVC 5.1.0.0 or later versions, except for CheckBox, which uses a div in bootstrapstring Booltype = "System.Boolean"; Version requiredmvcversion = new version ("5.1.0.0"); bool iscontrolhtmlattributessupported = Mvcversion >= requiredmvcversion;//the following chained if-statement outputs the file header code and markup for a partial view, a Vie W using a layout page, or a regular view.if (Ispartialview) {#><#} else if (islayoutpageselected) {#>@{ViewBag. Title = "<#= viewname#>";< #if (! String.IsNullOrEmpty (layoutpagefile)) {#> Layout = "<#= layoutpagefile#>"; <#}#>}Generated code:
edit.cshtmlOf course, the code also needs to be slightly modified. By adding a custom template page, as long as the background corresponding to the solid model has been built, in front of only need to create a new two custom views, a simple add and delete changes can be completed without writing a JS code.
Iii. Binding of Select componentsThe above describes the next T4 package additions and deletions of the syntax, the page all the components are basically text boxes, however, in the actual project, many of the query and editing pages will have a drop-down box display, for the dropdown box, we how to deal with it? No suspense, just give the solution, like edit page we can put the drop-down box's data source in the background.
User's entity
[DataContract] public class User { [DataMember] public int ID {get; set;} [DataMember] public string Name {get; set;} [DataMember] public string FullName {get; set;} [DataMember] public int Age {get; set;} [DataMember] public string Des {get; set;} [DataMember] Public DateTime createtime {get; set;} [DataMember] public string Strcreatetime {get; set;} [DataMember] public string DepartmentID {get; set;} [DataMember] Public object departments {get; set;} }
Then edit the page
Public ActionResult Edit (User model) { model. Departments = Departmentmodel.getdata (); return View (model); }
Then the front-end binding is ready.
<div class= "Form-group" > <label for= "txt_des" > Owning Department </label> <select id= "Sel_dept" class= "Form-control" data-bind= "options:editModel.Departments, optionstext: ' Name ', optionsvalue: ' Id ', value:editModel.DepartmentId "></select> </div>
JS code does not have to make any changes, add and edit when the Department field can be automatically added to the ViewModel inside.
Of course, many of our projects use the drop-down box is not a simple select, because the simple select style is really ugly, and then a lot of select components, such as the Bo master before sharing Select2, MultiSelect and so on. When using these components to initialize Select, the audit element you will find that the drop-down box on the interface is not simply a select tag, but rather consists of many other tags that the component customizes. Let's take the Select2 component as an example to see if it's possible to initialize directly as above.
We will edit the page initialization of the JS code to add the last sentence:
<script type= "Text/javascript" > $ (function () {var model = @Html. Raw ( Newtonsoft.Json.JsonConvert.SerializeObject (Model)); var ViewModel = { formId: "Formedit", Editmodel:model, URLs: { submit:model.id = = 0? "/user/add": "/user/update" }, validator:{fields : { Name: { validators: { notempty: { Message: ' The name cannot be empty! '}}}}} ; Ko.bindingeditviewmodel (ViewModel); $ ("#sel_dept"). Select2 ({}); }); </script>
By adding and editing discoveries, this is really possible! Parsing the reason, although the HTML of the page changes after the initialization of the SELECT2 component, the component eventually renders the selected value on top of the original select control. It is not known that other select initialization components, except for SELECT2, will be validated. But here's one thing to note, before initializing Select2, the options for the dropdown box must first bind the value, that is, the initialization of the component must be placed after ko.applybinding ().
Iv. SummaryAt this point, the bootstraptable template generation and the use of the Select control are basically available, of course, yet to be perfected. If there is time in the back, bloggers will tidy up other front-end components and Ko's combined use, such as our most common date controls. If you think this article is helpful, please feel free to recommend it.
Original source of this article: http://www.cnblogs.com/landeanfen/
Welcome to reprint, but without the author's consent, reprint article must be in the article page obvious location to the author and the original link , otherwise reserve the right to pursue legal responsibility
Bootstraptable+knockoutjs implementation of adding and deleting solutions