public virtual TModel Get <TModel>() { TModel model = default(TModel); var t = typeof(TModel); if (t.IsClass && t.IsPublic && !t.IsAbstract) { model = Activator.CreateInstance <TModel>(); ModelInfo info = GetModelInfo(t); if (info.PropertyDic != null && info.PropertyDic.Count > 0) { bool isUp = UpdateModel(model, info.PropertyDic, null); //if (isUp) //{ //} } } return(model); }
private bool UpdateModel(object model, Dictionary <string, ModelProperty> propertyDic, string prefix) { bool result = false; if (model != null && propertyDic != null && propertyDic.Count > 0) { if (prefix == null) { prefix = ""; } foreach (var kv in propertyDic) { var propertyType = kv.Value.PropertyInfo.PropertyType; if (propertyType.IsClass && !propertyType.IsArray && propertyType != typeof(string)) { if (propertyType.IsGenericType) { var ts = propertyType.GetGenericArguments(); if (ts != null && ts.Length == 1) { if (propertyType == typeof(List <>).MakeGenericType(ts)) { var list = Activator.CreateInstance(propertyType) as IList; var t = ts[0]; if (t.IsClass && !t.IsArray && t != typeof(string)) { var info = GetModelInfo(t); int i = 0; while (true) { var m = Activator.CreateInstance(t); if (UpdateModel(m, info.PropertyDic, prefix + kv.Key + "[" + i + "]")) { list.Add(m); } else { break; } i++; } } try { kv.Value.PropertyInfo.SetValue(model, list, null); result = true; } catch { } } } } else { ModelInfo info = GetModelInfo(propertyType); if (info.PropertyDic != null && info.PropertyDic.Count > 0) { object o = Activator.CreateInstance(propertyType); bool isUp = UpdateModel(o, info.PropertyDic, kv.Key + "."); if (isUp) { try { kv.Value.PropertyInfo.SetValue(model, o, null); result = true; } catch { } } } } } else if (propertyType.IsArray) { var ts = propertyType.GetGenericArguments(); if (ts != null && ts.Length == 1) { var t = ts[0]; var list_t = typeof(List <>).MakeGenericType(ts); var list = Activator.CreateInstance(list_t) as IList; var info = GetModelInfo(t); int i = 0; while (true) { var m = Activator.CreateInstance(t); if (UpdateModel(m, info.PropertyDic, prefix + kv.Key + "[" + i + "]")) { list.Add(m); } else { break; } i++; } try { var val = Array.CreateInstance(t, list.Count); list.CopyTo(val, 0); kv.Value.PropertyInfo.SetValue(model, val, null); result = true; } catch { } } } else { string val = this.m_controller.Form[prefix + kv.Key]; if (val == null) { val = this.m_controller.QueryString[prefix + kv.Key]; } if (val == null) { continue; } try { object o = ChangeType(val, propertyType); if (o != null) { kv.Value.PropertyInfo.SetValue(model, o, null); } result = true; } catch { } } } } return(result); }