ModelBinding
webform里面表单提交远远没有mvc表单提交方便,最明显的地方就是页面数据的传递,我找了一点代码,保存下,方便以后查阅。
#region 模型绑定(测试) //模型绑定的错误消息 public Dictionary<string, string> ErrorMsgs = new Dictionary<string, string>(); //是否验证通过 public bool IsValidated { get; set; } /// <summary> /// 手写模型绑定器--添加编辑数据时使用--对数据的验证不是很精确,主要还要依赖前台验证 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T ModelBinding<T>(params T[] entityP) { object entity = Activator.CreateInstance(typeof(T));//添加 if (entityP != null && entityP.Length > 0)//编辑 { entity = entityP[0]; } Type types = entity.GetType(); var pros = types.GetProperties(); Dictionary<string, System.Reflection.PropertyInfo> proNames = new Dictionary<string, System.Reflection.PropertyInfo>(); foreach (var p in pros) { proNames.Add(p.Name, p); } var forms = Request.Form; var keys = forms.AllKeys; foreach (var key in keys) { if (proNames.Keys.Contains(key)) { var pro = proNames[key]; var type = pro.PropertyType; var columnValue = forms[key]; if (string.IsNullOrEmpty(columnValue))//数据表列值不为空 { continue; } try { if (type.IsEnum)//若果属性是枚举类型 { pro.SetValue(entity, Enum.ToObject(type, columnValue), null); } else { if (type.IsGenericType && type.Name.StartsWith("Nullable"))//泛型类型 { type = Nullable.GetUnderlyingType(type); } pro.SetValue(entity, Convert.ChangeType(columnValue, type), null); } } catch (Exception ex) { ErrorMsgs.Add(key, ex.Message); } } } IsValidated = ErrorMsgs.Count > 0 ? false : true; return (T)entity; } #endregion
具体还在测试,

浙公网安备 33010602011771号