Json2Template. js is a Jquery plugin used to bind JavaScript objects to Html templates.
The Code is as follows:
$ ("# P"). bindTemplate ({
Source: json object,
Template: null | $ ("# template") |"
{Object }}
",
DateFormat: "d. m. y ",
TagOpen :"{{",
TagClose :"}}"
});
BindTemplate (data): Operation Method for binding a data object to a template
Source: Data source in json format
Template:
Null does not provide template, InnerHtml output
$ ("# Template") uses the html structure defined on the page as a template
"
{{...}}
"Directly define the Template
DateFormat: Time Format
TagOpen: start tag
TagClose: end tag
DateFormat, tagOpen, and tagClose all use the default configuration for null. It is necessary to say that the default tagOpen & tagClose is marked with "{" and "}".
Json2Template Application
Let's take a look at the simple usage of Json2Template through a small example.
Create an empty MVC3 Project
First, we need an object to store the transmitted data.
The Code is as follows:
Public class UserInfo
{
Public int ID {get; set ;}
Public string Name {get; set ;}
Public int Age {get; set ;}
Public string Address {get; set ;}
}
Virtualize a data set, because the actual application scenario is obtained by querying the database
The Code is as follows:
Private IList InitUserInfo ()
{
IList Users = new List ();
Users. Add (new UserInfo () {ID = 1, Name = "Chenkun", Age = 21, Address = "Suzhou "});
Users. Add (new UserInfo () {ID = 2, Name = "Zhangsan", Age = 21, Address = "Beijing "});
Users. Add (new UserInfo () {ID = 3, Name = "Lisi", Age = 21, Address = "Henan "});
Users. Add (new UserInfo () {ID = 4, Name = "Wangwu", Age = 21, Address = "Shanghai "});
Users. Add (new UserInfo () {ID = 5, Name = "Zhaoliu", Age = 21, Address = "Guangzhou "});
Users. Add (new UserInfo () {ID = 6, Name = "Huqi", Age = 21, Address = "Chongqing "});
Return users;
}
These basic items are ready. We need to serialize the set to json and provide it to Json2Template. Here we use Newtonsoft. Json! Here we need to define an Action
The Code is as follows:
Public JsonResult GetUserInfo ()
{
Return Json (Newtonsoft. Json. JsonConvert. SerializeObject (InitUserInfo (), JsonRequestBehavior. AllowGet );
}
Serialize our collection to json and enable Get request so that ajax can call it through Get
After adding a reference to json2template. js, we will initiate an ajax request to obtain the json data in the background, and then use bindTemplate to display the obtained data in the HTML template.
First, we define a simple HTML template:
The Code is as follows:
No. |
Name |
Age |
Address |
{ID }} |
{Name }} |
{Age }} |
{Address }} |
{Note: defining {item} in class indicates traversing the subset of the item object similar to forearch}
Define another html container used to output this template
The Code is as follows:
Finally, request json data and help set the template according to the method we have designed in advance.
The Code is as follows: