邏輯比較複雜的Form綁定起來比較麻煩,這些都是要自己寫代碼。而簡單的我們可以寫一個通用的 進行處理。不需要反覆的 xxx.Text = "xxx" ..
MVC有自己的自動對應功能,我們這 裡用jQuery來遍曆Controls進行綁定。
如果用過asp開發過系統的人都知道以前取表單的值都是 request.form("controlName"),用到的是name而不是id。
所以我們的表單在製作的 時候元素的Name值不能沒有。 為了能夠寫通用的方法,我們約定所有的元素的name 是 "cName" 格式 ,"c"+"欄位名",id自己隨便。
由於Js的 Dictionary區分大小寫,所以我們這些名字也對大小寫敏感,包括上一節的列表綁定都是這樣。
Code
$.fn.bindForm = function(model) {
if (model == undefined || model == null) {
return;
}
var formId = this.attr("id");
$("input,textarea,select", "#" + formId).each(function() {
var cname = $(this).attr ("name");
var cid = $(this).attr("id");
if (cname == "")
return;
if (cid == "") {
cid = $(this)[0].tagName + "[name='" + cname + "']";
$(this).attr("id", cname);
} else
cid = "#" + cid;
$(cid).bindControl(model[cname.replace ("c", "")], formId);
});
return this;
Code
$.fn.bindControl = function(value, formId) {
if (value == undefined)
return this;
value = value.toString();
formId = formId || "";
if (formId != "")
formId = "#" + formId + " ";
switch (this.attr("type")) {
case "select-one": //DropDownList
//this[0].selectedIndex = 0;
//$("option[value='" + value + "']", this).attr("selected");
var isSelected = false;
this.children().each(function() {
if (this.value == value) {
this.selected = true;
isSelected = true;
return;
}
});
if (!isSelected)
this[0].selectedIndex = 0;
break;
case "select-multiple": //ListBox
this.children().each(function() {
var arr = value.split(',');
for (var i = 0; i < arr.length; i++) {
if (this.value == arr[i]) {
this.selected = true;
}
}
});
break;
case "checkbox": //CheckboxList
//單選
if (value.indexOf(',') == -1) {
$(formId + "input[name='" + this.attr("name") + "'] ").each(function() {
if (this.value == value) {
$(this).attr ("checked", true);
return;
}
});
}
//多選
else if (this.attr("type") == 'checkbox') {
var arr = value.split(',');
for (var i = 0; i < arr.length; i++) {
$(formId + "input[name='" + this.attr("name") + "']").each (function() {
if (this.value == arr [i]) {
this.checked = true;
}
});
}
}
break;
case "radio": //RadioButtonList
$(formId + " input[name='" + this.attr ("name") + "']").each(function() {
if (this.value == value) {
this.checked = true;
return;
}
});
break;
default: //Normal
this.val(value);
break;
}
return this;
}
綁定表單就 顯得比較容易了。
$("#form1").bindForm(<%=Json(ViewData ["model"])%>); 簡單的一句話,就自動把值綁定了。
綁定一個控制項也很容易 $("#controlId").bindControl(value);
其實在實際開發中,我們會經常碰到 級聯 的DropDownList , 這樣在綁定的時候 我們還要對具體的Control 執行綁定,並且trigger他的event 。 這個叫雙向繫結,目前還沒做成自動化。