本章介绍如何在生成表单后,将一个model的数据展示到form表单中(一般用于编辑页面)
代码如下(连接地址:https://github.com/xiexingen/Bootstrap-SmartForm/blob/master/demo/form4-initData.html):
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>数据绑定</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/bootstrap.css">
<!--自定义站点样式-->
<link rel="stylesheet" href="../css/site.css">
<script src="../lib/jquery.js"></script>
<script src="../lib/bootstrap.js"></script>
<!--工具方法-->
<script src="../scripts/global.js"></script>
<!--插件-->
<script src="../scripts/plugin.js"></script>
</head> <body>
<div class="panel panel-default">
<div class="panel-heading">
<label>数据绑定</label>
<div class="pull-right">
<button id="btnSubmit" class="btn btn-primary btn-xs">提交表单</button>
</div>
</div> <div class="panel-body">
<form action="#" id="formContainer" class="form form-horizontal"></form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading"><label>介绍</label></div>
<div class="panel-body">
<h3 class="lead">表单数据绑定</h3>
<blockquote>
<p>将json格式的model绑定到表单中,此处使用模拟的model数据,实际环境中应该是与服务器交互取到数据,在配置对象的是需要一个回调方法,在回到方法里面可以做表单的一些其他操作,如添加表单验证、添加日期插件的支持====</p>
<p>note:复选框的数据源为数组形式</p>
</blockquote>
</div>
</div>
<script>
$(function () {
var eles=[
[
{label:{text:'自定义用户名:'},ele:{type:'text',name:'UserName',title:'用户名:',required:true}},
{ele:{type:'radio',name:'sex',title:'性别:',items:[{text:'男',value:1},{text:'女',value:2}]}},
{ele:{type:'checkbox', name:'plant',title:'使用平台:',items:[{text:'APP',value:'app'},{text:'web',value:'web'}]}}
],
[
{ele:{type:'select',name:'province',title:'省份:',withNull:true,items:[{text:'广东',value:'GD'},{text:'湖南',value:'HN'}]}},
{ele:{pre:{text:'<input type="radio">'},type:'text',name:'displayName',title:'显示名称:'}},
{ele:{type:'search',title:'产品',id:'ProductName'}}
],
[
{ele:{type:'datetime',name:'FromeDate',title:'有效期:'}},
{ele:{type:'datetime',name:'ToDate',title:'~'}},
]
];
//隐藏表单元素主要用于编辑时候后台可以区别开来
var hides = [{ id: 'primaryKey' }];
var bsForm = new BSForm({ eles: eles, hides: hides, autoLayout: '1,3' }).Render('formContainer',function(bf){
var model={primaryKey:1,UserName:'xxg',sex:1,plant:['app','web'],province:'GD',displayName:'TEST',ProductName:'笔记本',FromeDate:'2015-06-10',ToDate:'2015-08-08'};
bf.InitFormData(model);
}); $("#btnSubmit").bind('click',function () {
var postData=bsForm.GetFormData();
alert("获取到的表达数据为:"+JSON.stringify(postData));
})
});
</script>
</body></html>
此处使用js创建了一个json类型的model,实际开发情况下 会跟服务器交互得到一个model,通过表单插件的InitFormData方法将model显示到form表单中
效果图如下:
定义的数据成功显示到表单中,
note:针对复选框多选的情况下,需要返回的是一个数组