·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> .net的WebForm模拟MVC进行模型绑定,让自己少操劳

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

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23
.net的WebForm模拟MVC进行模型绑定,让自己少操劳

用过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框架进行验证表单再提交到后台,这里就不再多说了,大家明白如何使用这个方法就好,有不完善的地方希望大家指出!