c# 之HttpContext通过表单提交后批量转换为Model

来源:互联网 发布:linux注释#作用 编辑:程序博客网 时间:2024/06/06 03:13

最近开发借助DWZ+.net,涉及到表单提交这一块,通过ashx来实现异步(ajax)的提交和执行。

遇到的情况是表单有时候包括了太多的字段,这时候便开始想偷懒的法子了,直接借用泛型写了个批量转换的法子,前提是表单传参的参数名必须跟model名一致,代码如下:

public static class FormToModelHelper<T> where T: new()
    {
        public static T ConvertToModel(HttpContext context)
        {
            T t = new T();
            PropertyInfo[] propertys = t.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                if (!pi.CanWrite)
                    continue;
                object value = context.Request[pi.Name];
                if (value != null && value != DBNull.Value)
                {
                    try
                    {
                        if (value.ToString() != "")
                            pi.SetValue(t, Convert.ChangeType(value, pi.PropertyType), null);//这一步很重要,用于类型转换
                        else
                            pi.SetValue(t, value, null);
                    }
                    catch
                    { }
                }
            }
            
            return t;
        }
    }


调用方法如下:

Model.Users model = new Model.Users();

model = FormToModelHelper<Model.Users>.ConvertToModel(context);//context 为ashx里的HttpContext


表达可能欠妥,都怪时间太窄,指缝太宽~~~




0 0