首页 > 编程 > .NET > 正文

ASP.NET中实现Form表单字段值自动填充到操作模型中

2024-07-10 12:47:52
字体:
来源:转载
供稿:网友

我们知道ASP.NET MVC有个强大的地方就是Form表单提交到action的时候,可以直接将Form的参数直接装配到action的参数实体对象中

比如
代码如下:
action方法 Register(UserModel userModel)

{

   ............................. 

}

在提交表单的时候,会自动讲表单里面的字段封装到对应的UserModel字段里面

那么 WebForm里面可不可以也紫将呢?

因为每次都要去获得数据,优秀的程序员应该要学会代码封装,代码复用,重复的工作不要做

我们其实可以利用反射来实例化对象的(自动装配)

好了废话不多....

pageload里面很简单了
代码如下:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPost())
            {
                InitPage();//第一次访问呈现页面
            }
            else
            {
                UserModel userModel = AssembleModel<UserModel>(base.valueCollection);
            }
        }

关键就是基类里面的AssembleModel 方法了

基类里面

我们首先获取到上下文的参数 IT404
代码如下:
protected NameValueCollection valueCollection = HttpContext.Current.Request.Params;

基类很简单,就是将上下文的提交的参数存放到valueCollection

然后再看AssembleModel方法了,这是一个泛型方法

代码如下:
/// <summary>
        /// 反射获取类的属性
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected PropertyInfo[] GetPropertyInfoArray(Type type)
        {
            PropertyInfo[] props = null;
            try
            {
                object obj = Activator.CreateInstance(type);
                props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表