MVC+jQuery开发B/S系统②:表单绑定

标题冠名MVC其实跟MVC没多大关系了。。 目前只是写的前台,请求的都是后台给的Json数据。

逻辑比较复杂的Form绑定起来比较麻烦,这些都是要自己写代码。而简单的我们可以写一个通用的进行处理。不需要反复的 xxx.Text = "xxx" ..

MVC有自己的自动映射功能,我们这里用jQuery来遍历Controls进行绑定。
如果用过asp开发过系统的人都知道以前取表单的值都是request.form("controlName"),用到的是name而不是id。
所以我们的表单在制作的时候元素的Name值不能没有。 为了能够写通用的方法,我们约定所有的元素的name 是 "cName" 格式 ,"c"+"字段名",id自己随便。
由于Js的Dictionary区分大小写,所以我们这些名字也对大小写敏感,包括上一节的列表绑定都是这样。
代码
; (function($) {
$.fn.bindForm
= function(model) {
if (model == undefined || model == null) {
return this;
}
var me = this;
var formId = this.attr("id");
$(
"input,textarea,select", me).each(function() {
var cname = $(this).attr("name");
$(
this).bindControl(model[cname.replace("c", "")], me);
});
return this;
};
})(jQuery);

 

代码
; (function($) {
$.fn.bindControl
= function(value) {
var me = this;
if (value === undefined || value === null)
return this;
value
= value.toString();

switch (me.attr("type")) {
case "select-one": //DropDownList
//this[0].selectedIndex = 0;
//$("option[value='" + value + "']", this).attr("selected");
var isSelected = false;
me.children().each(
function() {
if (this.value == value) {
this.selected = isSelected = true;
return;
}
});
if (!isSelected)
me[
0].selectedIndex = 0;
break;
case "select-multiple": //ListBox
var arr = value.split(',');
me.children().each(
function() {
for (var i = 0; i < arr.length; i++) {
if (this.value == arr[i]) {
$(
this).attr("selected", "selected");
}
}
});
break;
case "checkbox": //CheckboxList
//单选
if (value.indexOf(',') == -1) {
me.each(
function() {
if (this.value == value) {
this.checked = true;
return;
}
});
}
//多选
else if (this.attr("type") == 'checkbox') {
var arr = value.split(',');
for (var i = 0; i < arr.length; i++) {
me.each(
function() {
if (this.value == arr[i]) {
this.checked = true;
}
});
}
}
break;
case "radio": //RadioButtonList
me.each(function() {
if (this.value == value) {
this.checked = true;
return;
}
});
break;
default: //Normal
this.val(value);
break;
}

return this;
};

})(jQuery);

 

绑定表单就显得比较容易了。 
$("#form1").bindForm(<%=Json(ViewData["model"])%>); 简单的一句话,就自动把值绑定了。
绑定一个控件也很容易 $("#controlId").bindControl(value); 
其实在实际开发中,我们会经常碰到 级联的DropDownList , 这样在绑定的时候 我们还要对具体的Control 执行绑定,并且trigger他的event。 这个叫双向绑定,目前还没做成自动化。
posted @ 2009-09-11 17:02  君之蘭  阅读(2714)  评论(3编辑  收藏  举报