页面控件内容向Model对象赋值

上篇文章写的是 Model对象中的值向页面控件赋值.

本篇文章则与之相反,页面控件中的向Model对象赋值.

不多说......code!

cs代码:

View Code
 1     protected void Button1_Click(object sender, EventArgs e)
2 {
3 TestModel model2 = new TestModel();
4 SetControlToModel(model2);
5 Response.Write("userid:"+model2.Userid);
6 Response.Write("</br>");
7 Response.Write("Username:" + model2.Username);
8 Response.Write("</br>");
9 Response.Write("Userpwd:" + model2.Userpwd);
10 }

逻辑代码:

View Code
1  ///<summary>
2 /// 需要赋值的Model对象
3 ///</summary>
4 ///<param name="model"></param>
5 ///<returns></returns>
6 public object SetControlToModel(object model)
7 {
8 return SetControlToModel(model, this);
9 }

核心代码:

View Code
  ///<summary>
/// 向Model赋值
///</summary>
///<param name="model">Model对象</param>
///<param name="ParentControl">页面控件 page,Panel 等控件</param>
///<returns></returns>
private object SetControlToModel(object model, Control ParentControl)
{
if (model == null) return null;
Type t = model.GetType();
PropertyInfo[] info = t.GetProperties();
foreach (PropertyInfo p in info) //得到Model中的属性
{
Control c;
Type type;
c = this.checkControl(p.Name, ParentControl); //检查控件是否存在
if (c != null)
{
type = c.GetType();
if (type.Equals(typeof(TextBox)))
{
SetValue(model, p, ((TextBox)c).Text.Trim());
}
if (type.Equals(typeof(DropDownList)))
{
SetValue(model, p, ((DropDownList)c).Text.Trim());
}
}
}
return model;
}

private void SetValue(object model,PropertyInfo info,object value)
{
if (value == DBNull.Value || value == null)
{
info.SetValue(model, null, null);
}
else
{
info.SetValue(model, Convert.ChangeType(value, GetPropertyType(info)), null);
}
}
///<summary>
/// 获得类型的真正类型
///</summary>
///<param name="propertyType"></param>
///<returns></returns>
private Type GetPropertyType(PropertyInfo p)
{
Type propertyType = p.PropertyType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
return propertyType;
}

完成!!!

看显示效果

点击 按钮后,成功输出:

最后,代码很多地方没有进行数据校验,提供方法及思路,自己完善吧!

源码地址:https://files.cnblogs.com/xyong/Demo_BindControl2.zip
 


作者:javaoraspx
出处:http://www.cnblogs.com/xyong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/xyong/p/2229855.html