页面控件内容向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;
}

完成!!!

看显示效果

点击 按钮后,成功输出:

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

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

转载于:https://www.cnblogs.com/xyong/archive/2011/10/31/2229855.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值