Recently joined the Gut project, learned a lot of other colleagues write code, feel benefited.
In the gut project, you often encounter the problem of dynamically generating tables, including reading data from a database, binding it in a table, and adding a delete table from a page via jquery. As shown below:
In the implementation process, developers often implement the following methods:
1) in the foreground, the HTML string of the table row is generated by JS and then added to the bottom of the table through the jquery after method.
2) in the background, read the database, then generate the HTML string for the table, and then pass it to the foreground render
3) The benefit of doing so is that the effect of the table can be implemented without flushing
This realization has the following problems (of course, personal opinion, only for technical exchange ^_^):
1) Code duplication. The front desk wrote the table created JS, backstage and wrote again
2) string concatenation. When creating a background, a large number of concatenation of strings is used to implement the HTNL string of the table, which not only affects efficiency, but also is not easy to debug. such as missing a quotation mark, etc., not easy to find out. (about efficiency issues, because strings are constant in. NET, so if you do a lot of string concatenation, it will result in a waste of data and efficiency underground)
3) Bind the tabular data and get the table data to write a lot of code, assuming that the table has 10 column fields, it is necessary to write about the 10 columns of data how to get, and how to bind the table.
4) Developers often write database access operations in. aspx pages, which also does not conform to the spirit of MVC's separation of concerns. If the project is replaced by a different database, such as Oracle (in terms of the amount of data in the project, and the likelihood of a change to the database is not excluded in the future), then the developer will need to modify the database-related statements in the project.
--------------------------------------Split Line------------------------------------------
As mentioned earlier, you can think of a few ideas as follows:
1) can only write some JS script on the page to create the table, and in the background just provide to create the tabular data. That is, the background to get the data, and then to the foreground to call the JS function to create the table. This avoids having to write two times on both front and back. And it doesn't create HTML strings for tables in the background with a lot of string concatenation.
2) is it possible to do this in a different way, instead of creating a table with string concatenation? Like Jquery.html ()?
3) is it possible to provide a uniform way to create tables, bind tables, and get tabular data? Avoid writing so many codes each time to create a table.
Based on these ideas, I have developed a demo that enables you to dynamically create a table with less code, bind tabular data, get tabular data, and save it in a database. And the code can be reused.
--------------------------------------Split Line------------------------------------------
Pre-Preparation:
1) Create DATABASE test, add table person
2) Create entities layer, DAL layer, BLL layer
Entities layer (automatically generated via T4 template)
Using System;
Using Mybasiclib;
Using MyBasicLib.Data.ORMLiteNew;
Namespace ATMB. DCMS. Entities
{
<summary>
///
</summary>
[Serializable]
[Table (tablename= "person", keyname= "ID")]
public partial class Person:basetable
{
<summary>
///
</summary>
Public person ()
{
}
#region Public Properties
<summary>
///
</summary>
public override String ID
{
Set; get;
}
<summary>
///
</summary>
Public String Name
{
Set; get;
}
<summary>
///
</summary>
Public String Age
{
Set; get;
}
<summary>
///
</summary>
Public String Sex
{
Set; get;
}
<summary>
///
</summary>
Public String Location
{
Set; get;
}
#endregion
}
}
Dal layer, implement a new, batch new, delete, get all the data of a few simple methods
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using ATMB. DCMS. entities;
Using MyBasicLib.Data.ORMLiteNew;
Namespace DAL
{
public class Personda
{
public void Add (person p)
{
using (var dc = new DataContext ())
{
dc. Insert (P);
dc. SubmitChanges ();
}
}
public void Add (list<person> ds)
{
using (var dc = new DataContext ())
{
foreach (Var p in DS)
{
dc. Insert (P);
}
dc. SubmitChanges ();
}
}
public void Delete ()
{
using (var dc = new DataContext ())
{
dc. Delete<person> (p =!) Sqlmethods.isnull (p.id));
dc. SubmitChanges ();
}
}
Public list<person> GetList ()
{
using (var dc = new DataContext ())
{
Return DC. Gettable<person> (). ToList ();
}
}
}
}
BLL Layer
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using ATMB. DCMS. entities;
Using DAL;
Namespace BLL
{
public class PERSONBLL
{
Personda da;
Public Personbll ()
{
da = new Personda ();
}
public void Add (list<person> ds)
{
Da. Delete ();
Da. Add (DS);
}
Public list<person> GetList ()
{
Return DA. GetList ();
}
}
}
Note: Database access using LINQ, and other methods such as OLE DB, as long as you modify the DAL layer.
3) dynamic creation of tables via JS
First step: Define the table
Here are a few places to be aware of:
First: The table added on the page, I added two tr, one is the display of the TR, with the "new" icon. The other is a hidden, template that is used as a new row. In this way, it is not easy to make mistakes and avoid creating them through strings.
Second: In the TR shown, a class called "Targettr" is set, which is used to search all the rows of the table, which is used later.
Thirdly, in each TD, a new tag property, corresponding to the actual field of the database table, is added to automatically obtain and bind the tabular data.
The ID of each input of the TR template (or any other attribute that needs to be replaced) is defined as the xxx_x,_x suffix to replace. For example, the addition of a TR, the sequence number is 3, you want to replace the TR in the _x suffix of each input is _3. Such.
Step two: Implement the JS method for adding and deleting table rows
The changeattr is implemented as follows:
The CHANGEATTR is primarily implemented with the _x end of the replacement input property as a specific ordinal number.
This enables the addition and deletion of table rows on the page. Through the definition of the template, we do not need to write the new TR HTML string in JS. This can minimize the likelihood of errors occurring. Because the readability of the string is poor, debug is more difficult.
Next, to achieve the background to obtain tabular data, and then through the above several JS script dynamically generated tables.
First introduce the realization of the idea
The first step, look. Implementation in ASHX
The implementation in ASHX is simple, which is to do the corresponding operation according to the request of the foreground, and then return the result (JSON) to the foreground
Step two: The foreground is accessed via Ajax. ASHX, get Tabular data
Success, the data in the table is returned in JSON format (such as a person's collection), and the foreground parses the JSON data and creates a table.
Bindtable implementation is very simple, first look at the total number of data, and then call the Add_tr method several times, add tr. (Because the first TR is present by default, so long as it is called json.length-1 times)
The next step is the core of the feature, which binds the data of the table. Just call a function here to Bindtablevalue, which is implemented as follows
This function can implement data binding for any table. can be reused completely. There are, of course, some flaws. This article will be explained at the end.
The process of getting a value from a database and then dynamically drawing a table is implemented over and over. The entire process is not implemented for a specific table, so the code can be reused. Another benefit of this implementation process is that the separation of concerns. For the presentation layer (foreground, web layer), it is only concerned with the corresponding presentation based on the data, and does not care how the data comes (from SQL, or Oracle?). In what way). The BLL layer is responsible for returning data based on the user's request. Focus on the processing of business logic. This implementation does not write any SQL statements in the foreground. The code looks more concise.
Finally, the implementation saves the modified tabular data back to the database. It's easier.
When you click Save, the Save method is called. The core of the Save method is the first sentence:
The implementation of Gettablevalue is:
--------------------------------------Split Line------------------------------------------
Summarize:
- In this way, the dynamic drawing of the table, the automatic binding of data and the automatic acquisition are realized by means of reusable, extensible and separating the focus points. And the user's code volume has been reduced a lot compared to the past.
- There are still some deficiencies in the method of automatic binding and fetching, because the implementation of the current version is only based on the string type. The type of datetime,bool,int is not considered. But depending on the principle of separation of concerns (or dependency inversion principle), we can also separate that part of logic from the classes that specialize in data types to handle. Then keep the original logic intact. I will continue to improve.
- This method also applies to the preservation and binding of form data.
- Experience: Less Code, less Copy, more reuseable, more flexiable and more OO.
Dynamic creation of tables based on jquery, automatic binding, automatic acquisition of values