码迷,mamicode.com
首页 > Web开发 > 详细

.net的WebForm模拟MVC进行模型绑定,让自己少操劳

时间:2015-07-31 17:39:19      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

用过MVC的兄弟们都知道,MVC有模型绑定表单提交的数据功能,那么我也想偷个懒也写个WebForm版的模型绑定。这里主要定义一个泛型方法,然后通过反射把表单上对应属性名字的值赋值到反射创建类的属性上。

有注意的地方:

1、定义的模型类的属性名要和表单name的名字相对应

2、定义的泛型方法是通过 var form = context.Request.Form;   表单 POST过来的数据

public class DataModel
{

    /// <summary>
    /// 从表单提交的数据中绑定model模型的值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="entity"></param>
    /// <returns></returns>
    public static T ModelBing<T>(T entity)
    {
        object obj = Activator.CreateInstance(typeof(T));
        Type type = entity.GetType();
        PropertyInfo[] proInfos = type.GetProperties();
        Dictionary<string, PropertyInfo> dic = new System.Collections.Generic.Dictionary<string, PropertyInfo>();
        for (int i = 0; i < proInfos.Length; i++)
        {
            dic.Add(proInfos[i].Name, proInfos[i]);
        }
        HttpContext context = HttpContext.Current;
        var form = context.Request.Form;
        string[] keys = form.AllKeys;

        foreach (string key in keys)
        {

            if (dic.ContainsKey(key))
            {
                PropertyInfo pInfo = dic[key];
                var proType = pInfo.PropertyType;
                object value = null;//存储转换对应类型后的值

                if (string.IsNullOrEmpty(form[key]))//当post过来的值没有的时候
                {
                    if (proType == typeof(string))  //判断该属性是否string类型给空字符串,因为我数据库该字段不允许为null
                    {                                 //这里我不对值类型的数据进行判断了,因为值类型会有默认值
                        pInfo.SetValue(obj, "", null);
                    }                                       
                    continue;
                }
                try
                {
                    if (proType.IsEnum)//如果属性是枚举类型,转换枚举类型
                    {
                        value = Enum.ToObject(proType, form[key]);

                    }
                    else if (proType.IsGenericType && proType.Name.StartsWith("Nullable"))//泛型类型
                    {
                        Type newproType = Nullable.GetUnderlyingType(proType);

                        value = Convert.ChangeType(form[key], newproType);
                    }
                    else
                    {
                        value = Convert.ChangeType(form[key], proType);
                    }

                    pInfo.SetValue(obj, value, null);
                }
                catch (Exception ex)
                {

                    throw ex;//写入错误日志
                }


            }
        }
        return (T)obj;
    }
}

 

前台可以通过EasyUI框架进行验证表单再提交到后台,这里就不再多说了,大家明白如何使用这个方法就好,有不完善的地方希望大家指出!

.net的WebForm模拟MVC进行模型绑定,让自己少操劳

标签:

原文地址:http://www.cnblogs.com/kesimin/p/4692620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!