ASP.NET From表单转实体类
2024-10-18 00:47:48
原由
经常遇到 int Age=Convert.ToInt32(this.txtAge.Text);
这种蛋疼的代码,特写次方法。
之所以抛出异常是希望知道转换失败,格式错误的属性是什么,方便调试。
新版本
//新版本,可以再globa.ascx里面设置开发模式
//以便于调试错误
//表单转实体对象V2版
public class HttpRequestHelper
{
/// <summary>
/// 开发模式,设置成开发模式后抛出异常,可查看出错的属性,和类型
/// </summary>
public static bool DevMode { get; set; }
#region 表单转换成实体模型
/// <summary>
/// 表单转换成实体模型
/// 用法:1、插入,先new一个对象传入;
/// 2、更新,先从数据库查出这个对象传入
/// </summary>
/// <param name="obj">泛型对象</param>
/// <returns></returns>
public static T ConvertForm2Model<T>(T obj)
{
if (null == obj)
{
obj = default(T);
obj = Activator.CreateInstance<T>();
}
Type type = typeof(T);
foreach (var p in type.GetProperties())
{
string result = HttpContext.Current.Request.Params[p.Name];
if (!string.IsNullOrWhiteSpace(result))
{
try
{
p.SetValue(obj, Convert.ChangeType(result, p.PropertyType), null);
}
catch(Exception ex)
{
if (DevMode)
{
throw new Exception("类型转换错误,变量:" + p.Name + ",类型:" + p.PropertyType + ",错误信息:" + ex.Message);
}
else
{
//记录日志。。。。 }
}
}
}
return obj; }
#endregion
}
旧版本
//////////////////
///各位有什么好想法,请给个建议
//460247986@qq.com
////////////////// public class HttpRequestHelper<T> where T : class,new()
{
#region 表单转换成实体模型
/// <summary>
/// 表单转换成实体模型
/// 用法:1、插入,先new一个对象传入;
/// 2、更新,先从数据库查出这个对象传入
/// </summary>
/// <param name="obj">泛型对象</param>
/// <returns></returns>
public static T ConvertForm2Model(T obj=null)
{
if (null == obj)
{
obj = default(T);
obj = Activator.CreateInstance<T>();
}
Type type = typeof(T);
foreach (var p in type.GetProperties())
{
string result = HttpContext.Current.Request.Params[p.Name];
if (!string.IsNullOrWhiteSpace(result))
{
try
{
p.SetValue(obj, Convert.ChangeType(result, p.PropertyType), null);
}
catch(Exception ex)
{
throw new Exception("类型转换错误,变量:" + p.Name + ",类型:" + p.PropertyType+",错误信息:" + ex.Message);
}
}
}
return obj; }
#endregion
}
最新文章
- I/O多路复用
- css 去除input 获取焦点的蓝色边框
- Educational Codeforces Round 7 F - The Sum of the k-th Powers 拉格朗日插值
- Linux系统编程(4)——文件与IO之ioctl函数
- hbase 二级索引创建
- 自己动手写CPU之第六阶段(2)——移动操作指令实现思路
- wIndows phone 7 解析Html数据
- 记录一下Fedora21下安装Foundation5遇到的问题[尚有遗留问题]
- POJ 3041 Asteroids(匈牙利+邻接表)
- php - preg_match
- word:Can&#39;t find the word document templant:WordToRqm.doc
- java学习笔记(详细)
- 老师博客copy
- PHP之十六个魔术方法
- Linux 重启nginx
- CentOS Tomcat启动 Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
- 使用sql获取primary key名称
- 使用HTML5开发离线应用 - cache manifest
- MFC中创建多线程
- JDK7 AutoCloseable