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。 这个叫双向绑定,目前还没做成自动化。
分类:
Javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?