Bootstraptable+knockoutjs of the combination of the implementation of the deletion of the solution (iii) two ViewModel to check and delete the _javascript skills

Source: Internet
Author: User
Tags button type

Preface: Before the blogger shared some basic usages of knockoutjs and bootstraptable, they were all written based applications, not encapsulation at all, just to avoid the value and assignment of HTML controls, and far from the subtle display of MVVM. Recently, the project intends to formally use the KO, so the KO and bootstraptable do some encapsulation, in this share out for the friends of the park for reference. Packaging Ideas Reference Blog Park great God Xiangin, if the park friends have a better way, welcome to discuss.

Knockoutjs Series Articles:

Combination of bootstraptable and Knockoutjs to realize the function of "one"

Combination of bootstraptable and Knockoutjs to realize the function of "two"

One, the first viewmodel to fix the query

Demo implementation or continuation of the last Department management function. The following expansion is illustrated by data flow.

1, backstage to view return to the ViewModel realization

Public ActionResult Index ()
{
var model = new
{
tableparams = new
{
url = '/department/ Getdepartment ",
//pagesize = 2,
},
urls = new
{
delete ="/department/delete ",
edit ="/ Department/edit ",
add ="/department/edit ",
},
querycondition = new
{
name =" ",
des =" "
}
};
return View (model);
}

Code explanation: The model returned here contains three options

tableparams: Page table initialization parameters. Because the default parameters are defined in JS, the parameters set here are page-specific initialization parameters.

URLs: Contains the URL path to delete and modify the request.

Querycondition: The query criteria for the page.

2, cshtml page code

The index.cshtml page code is as follows:

@{Layout = null;} <! DOCTYPE html>  

Code explanation: As in the previous article, you need to refer to jquery, Bootstrap, bootstraptable, knockout, and other related documents. The following two documents are highlighted here:

knockout.index.js: Encapsulates the properties and event bindings associated with the query page.

Knockout.bootstraptable.js: Encapsulates the method of bootstraptable initialization and custom knockout binding.

All of the above page interaction is encapsulated in the public JS inside, so you do not have to write a large number of DOM elements on the page to assign value, event binding, such as duplication of code, need to write in this page JS only the above two sentences, is very easy.

3, JS Package

Focus on the above said two JS files Knockout.bootstraptable.js and Knockout.index.js.

(1) Knockout.bootstraptable.js

(function ($) {//Add a Bootstraptableviewmodel method to Ko ko.bootstraptableviewmodel = function (options) {var "= this; t His.default = {toolbar: ' #toolbar ', which container is used by the tool button Queryparams:function (param) {return {limit:param.limit, Offset:para
M.offset}; },//Pass Parameters (*) pagination:true,//whether to display paging (*) sidepagination: "Server",//Paging: Client client paging, Server service end Paging (*) pagenumber:1,// Initialize load first page, default first page pagesize:10,//number of rows per page (*) PageList: [10, 25, 50, 100],//selectable number of rows per page (*) method: "Get", search:true,//whether display Form search, this search is the client search, will not enter the service side, so, personal sense is not very strictsearch:true, showcolumns:true,//whether to show all the columns Cache:false, showrefresh:true,//
Whether to show the refresh button minimumcountcolumns:2,//minimum allowable number of columns clicktoselect:true,//whether or not to enable clicking the selected row Showtoggle:true,}; This.params = $.extend ({}, This.default, Options | |
{});
The selected record this.getselections = function () {var arrres = that.bootstraptable ("getselections") return arrres;
Refresh This.refresh = function () {that.bootstraptable ("refresh");
}; Add KO Custom binding ko.bindingHandlers.bootstrapTable= {Init:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) {//The oparam here is bound viewModel var Oviewmodel = V
Alueaccessor ();
var $ele = $ (Element). bootstraptable (Oviewmodel.params); Add Bootstraptable method to ViewModel oviewmodel.bootstraptable = function () {return $ele. bootstraptable.apply ($ele,
arguments);
}, Update:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) {}};  }) (JQuery);

Code Explanation: The above code mainly does two things

1. Custom bootstraptable initialization ViewModel.

2.

Add KO custom bindings.

If your friends do not understand the use of custom bindings, you can look at the top two bloggers (i) and (ii), which are described in detail.

(2) Knockout.index.js

(function ($) {Ko.bindingviewmodel = function (data, bindelement) {var self = this; this.querycondition = ko.mapping.fr
OMJS (data.querycondition);
This.defaultqueryparams = {queryparams:function (param) {var params = self.querycondition; params.limit = Param.limit;
Params.offset = Param.offset;
return params;
}
}; var tableparams = $.extend ({}, This.defaultqueryparams, Data.tableparams | |
{});
this.bootstraptable = new Ko.bootstraptableviewmodel (tableparams); Empty Event This.clearclick = function () {$.each (self.querycondition, function (key, value) {//Only the Monitoring property clears if (typeof value)
= = "function") {this (');//value (');}});
Self.bootstrapTable.refresh ();
};
Query Event This.queryclick = function () {Self.bootstrapTable.refresh ();}; New Event This.addclick = function () {var dialog = $ (' <div class= "modal Fade" id= "Mymodal" tabindex= "-1" role= "dialog" a
Ria-labelledby= "Mymodallabel" ></div> ");
Dialog.load (data.urls.edit, NULL, function () {});
$ ("Body"). Append (dialog); Dialog.Modal (). On (' Hidden.bs.modal ', function () {//Close the pop-up box clears the bindings (this empty includes emptying the bindings and emptying the registration events) Ko.cleannode (document.getElementById (
"Formedit"));
Dialog.remove ();
Self.bootstrapTable.refresh ();
});
}; Edit Event This.editclick = function () {var arrselecteddata = self.bootstrapTable.getSelections (); if (Arrselecteddata.leng Th <= 0 | | Arrselecteddata.length > 1) {alert ("Edit only one row at a time"); return} var Dialog = $ (' <div class= modal fade ' id= ' Mymodal ' Tabi
ndex= "-1" role= "dialog" aria-labelledby= "Mymodallabel" ></div> ");
Dialog.load (Data.urls.edit, arrselecteddata[0], function () {});
$ ("Body"). Append (dialog); Dialog.modal (). On (' Hidden.bs.modal ', function () {///Close the pop-up box clears the bindings (this empty includes emptying the bindings and emptying the registration events) Ko.cleannode (
document.getElementById ("Formedit"));
Dialog.remove ();
Self.bootstrapTable.refresh ();
});
}; Delete Event This.deleteclick = function () {var arrselecteddata = self.bootstrapTable.getSelections (); if (!arrselecteddata| | arrselecteddata.length<=0) {alert ("Please select at least one row"); return;} $.ajax ({Url:data.urLs.delete, type: "Post", ContentType: ' Application/json ', data:JSON.stringify (Arrselecteddata), Success:function (
Data, status) {alert (status); Self.bootstrapTable.refresh ();}});
};
Ko.applybindings (self, bindelement);
};  }) (JQuery);

Code explanation: This JS mainly encapsulates the page element attributes and event bindings, need to explain several places

this.querycondition = Ko.mapping.fromJS (data.querycondition): The role of this sentence is to transfer the background of the query conditions, from the JSON data to monitor properties. Only by executing this sentence can the properties and page elements be monitored in both directions.

Self.bootstraptable.refresh (): The meaning of this sentence is to refresh the tabular data, which is actually called the Bootstraptable Refresh method, But the blogger in the Knockout.bootstraptable.js file inside the simple encapsulation of it.

dialog.load (data.urls.edit, NULL, function () {}): the jquery Load () method is used when adding and editing, and the method is to request the page element of this URL, and execute the URL corresponding to the page's JS code. This method is very powerful in dynamically referencing JS files and executing the code in the JS file.

Finally attach the background getdepartment () method corresponding to the code

[HttpGet]
Public jsonresult getdepartment (int limit, int offset, string name, String des)
{
var lstres = Departmentmodel.get Data ();
if (!string. IsNullOrEmpty (name)
{
lstres = lstres.where (x => x.name.contains (name)). ToList ();
}
if (!string. IsNullOrEmpty (des))
{
lstres = lstres.where (x => x.des.contains (DES)). ToList ();
}
Lstres.foreach (x=> {
x.strcreatetime = x.createtime.tostring ("Yyyy-mm-dd HH:mm:ss");
});
var ores = new
{
rows = Lstres.skip (offset). Take (limit). ToList (), Total
= Lstres.count
};
Return Json (ores, jsonrequestbehavior.allowget);

At this point, Query page query, empty function can be realized.

Do you still have a question: what if we need to customize the Bootstraptable event? Can't pass through the backstage ViewModel?

Indeed, from the background is unable to pass the JS event method, so we need to customize the event in front of the processing methods, such as we can:

<script type= "Text/javascript" >
$ (function () {
var data = @Html. Raw ( Newtonsoft.Json.JsonConvert.SerializeObject (Model));
data.tableParams.onLoadSuccess = function (data) {alert ("Load Success event"); };
Ko.bindingviewmodel (data, document.getElementById ("Div_index"));

Two, the second viewmodel finish editing

One of the above ViewModel the ability to query and delete, but the addition and editing will require another ViewModel support. Let's look at the encapsulation implementation of the edit.

1, the realization of ActionResult

From the code above, we can tell that when the user clicks Add and edit, he or she requests another view →/department/edit. Let's look at the implementation of Edit view

Public ActionResult Edit (Department model)
{
var oresmodel = new
{
Editmodel = model,
urls = New
{
submit = Model.id = 0? "/department/add": "/department/update"
}
};
Return View (Oresmodel);

Code Explanation: The above code is simply to return a viewmodel to the view page containing the edited entity and the submitted URL. Determine whether the current commit is a new entity or an edit entity through the existence of the entity primary key.

2, cshtml Code

The edit.cshtml code is as follows:

<form id= "Formedit" > <div class= "modal-dialog" role= "document" > <div class= "modal-content" > <div class= "Modal-header" > <button type= "button" class= "Close" data-dismiss= "modal" aria-label= "Close" ><span
Aria-hidden= "true" >x</span></button> 

Code Explanation: Because we add the validation component Bootstrapvalidator, so we need to reference the relevant JS and CSS. Knockout.edit.js This file mainly encapsulates the properties and event bindings of the edit page. Focus to see the implementation of this JS code.

3, JS Package

Knockout.edit.js Code:

(function ($) {
Ko.bindingeditviewmodel = function (data, validatorfields) {
var that = {};
That.editmodel = Ko.mapping.fromJS (Data.editmodel);
That.default = {Message
: ' Verify not Pass ',
fields: {},
submithandler:function (validator, form, Submitbutton) {
   var arrselecteddata = Ko.tojs (That.editmodel);
$.ajax ({
url:data.urls.submit,
type: "Post",
contentType: ' Application/json ',
data: Json.stringify (Arrselecteddata),
success:function (data, status) {
alert (status);
}
);
$ ("#myModal"). Modal ("Hide");
}
;
That.params = $.extend ({}, That.default, {fields:validatorfields} | | {});
$ (' #formEdit '). Bootstrapvalidator (that.params);
Ko.applybindings (That, document.getElementById ("Formedit"));

Code Explanation: This JS mainly encapsulates the editing model's properties and the committed event bindings. The form submission is required because the Bootstrapvalidator validation component is used. In fact, the public JS inside should not appear page ID, such as the above "Formedit" and "Mymodal", you can pass this as a parameter, this needs to be optimized. The parameter validatorfields represents the validation field of the validation component, and if the form does not require validation, it passes an empty JSON or does not pass. We have not done field validation, in general, the underlying table will have one or several non-null fields, such as we can add the department name of Non-null validation. Change the code in the Edit.cshtml page to this:

<form id= "Formedit" > <div class= "modal-dialog" role= "document" > <div class= "modal-content" > <div class= "Modal-header" > <button type= "button" class= "Close" data-dismiss= "modal" aria-label= "Close" ><span
Aria-hidden= "true" >x</span></button> 

Then it will be validated automatically at the time of submission:

Note: Verify that the property name corresponds to the Name property of the input label, so the Name property must be set correctly for verification.

It is best to attach the background method of additions and deletions:

[HttpPost]
Public Jsonresult Add (Department oData)
{
departmentmodel.add (oData);
Return Json (New {}, Jsonrequestbehavior.allowget);
}
[HttpPost]
Public Jsonresult Update (Department oData)
{
departmentmodel.update (oData);
Return Json (New {}, Jsonrequestbehavior.allowget);
}
[HttpPost]
Public Jsonresult Delete (list<department> oData)
{
departmentmodel.delete (oData);
Return Json (New {}, Jsonrequestbehavior.allowget);

At this point, our entire page additions and deletions to check the effect on OK, simple look at the effect:

Third, summary

The above simple encapsulation of the bootstraptable+ko of additions and deletions to check the business, just a primary encapsulation. If you need to use all of these in your project, you may need some simple optimization measures, such as:

1, if pure is a page of ViewModel, whether can not return from backstage actionresult inside, write directly in view page inside feel better, omit serialization and parameter pass problem. This has yet to be optimized.

2, the public JS should not appear in the page element ID, you can pass through the parameters of the page elements in.

3, add and edit event methods inside the pop-up box has a lot of duplicate code, this part of the best approach is to encapsulate the pop-up box into a separate component to invoke, you can reduce most of the JS code.

4, if the query conditions and edit the properties of the Select dropdown box elements, may also need to encapsulate the datasourse and other properties of the Drop-down box, this is a very common, such as Bo Master after the demo will add this piece.

The above is a small set to introduce the combination of Bootstraptable+knockoutjs to realize the solution (three) two ViewModel to check and delete, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.