$("#div").bindTemplate({
source : json object,
template : null | $("#template") | "
{{object}}
",
dateFormat : "d.m.y",
tagOpen : "{{",
tagClose : "}}"
});
bindTemplate(data): Operation method for binding data objects to templates
source : Data source in json format
template:
null No template is provided, InnerHtml outputs
$(“#template”) using the html structure defined on the page as a template
"
{{...}}
" Directly define template
dateFormat: time formatting method
tagOpen: starting tag tag
tagClose : Ending tag tag
Among them, dateFormat, tagOpen, tagClose can be null and adopt the default configuration. It is necessary to say that the default tagOpen & tagClose are marked with "{{" and "}}"
Application of Json2Template
Let’s take a small example to see the simple usage of Json2Template
Create an empty MVC3 project
First we need an object to store the passed Data
public class UserInfo
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Virtual data collection, because in actual application scenarios it is obtained by querying the database
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 things are ready. We need to serialize this collection into json and provide it to Json2Template. Here I use Newtonsoft.Json! Here we need to define an Action
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 pass Get method After calling
to add a reference to json2template.js, we start an ajax request to obtain the background json data, and then use bindTemplate to help determine the obtained data to be displayed in the HTML template
First we define a simple HTML template:
< div id="template-userinfo" style="display: none">
number | < th>NameAge | Address |
{{ID}} |
{{Name}} |
{{Age}} | {{Address}} |
{ Note: Defining {{item}} into class means traversing a subset of item objects, similar to forearch }
Finally, request the json data and help define the template in the way we imagined in advance