您现在的位置是:网站首页> 编程资料编程资料
ASP.NET中实现把form表单元素转为实体对象或集合_实用技巧_
2023-05-24
307人已围观
简介 ASP.NET中实现把form表单元素转为实体对象或集合_实用技巧_
简介:
做WEBFROM开发的同学都知道后台接收参数非常麻烦
虽然MVC中可以将表单直接转为集实,但不支持表单转为 LIST
单个对象的用法:
表单:
复制代码 代码如下:
后台:
复制代码 代码如下:
//以前写法
DLC_category d = new DLC_category();
d.sex = Request["sex"];
d.id = Convert.ToInt32(Request["id"]);
//现在写法
var category = RequestToModel.GetSingleForm
集合对象的用法:
表单:
复制代码 代码如下:
后台:
复制代码 代码如下:
List
源码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SyntacticSugar { /// /// ** 描述:表单帮助类 /// ** 创始时间:2015-4-17 /// ** 修改时间:- /// ** 作者:sunkaixuan /// ** qq:610262374 欢迎交流,共同提高 ,命名语法等写的不好的地方欢迎大家的给出宝贵建议 /// public class RequestToModel { /// /// 提交表单通过反射获取单个像 /// 注意:表单控件name必包含对应类中的第一个字段,否则将报错 /// public static T GetSingleForm() where T : new() { T t = SetList(null, 0).Single(); return t; } /// /// 提交表单通过反射获取单个像 /// 注意:表单控件name必包含对应类中的第一个字段,否则将报错 /// 控件前缀,比如 name="form1.sex" appstr可以设为form1 /// public static T GetSingleForm(string appstr) where T : new() { T t = SetList(appstr, 0).Single(); return t; } /// /// 提交表单通过反射获取多个对像 /// 注意:表单控件name必包含对应类中的第一个字段,否则将报错 /// /// /// /// public static List GetListByForm() where T : new() { List t = SetList(null, 0); return t; } /// /// 提交表单通过反射获取多个对像 /// 注意:表单控件name必包含对应类中的第一个字段,否则将报错 /// /// /// 控件前缀,比如 name="form1.sex" appstr可以设为form1 /// public static List GetListByForm(string appstr) where T : new() { List t = SetList(appstr, 0); return t; } /// /// 提交表单通过反射获取多个对像 /// /// /// 控件前缀,比如 name="form1.sex" appstr可以设为form1 /// 表单控件中第一个控件,对应类中字段在该类中的索引号,特殊情况可以是第二第三控件 /// private static List GetListByForm(string appstr, int index) where T : new() { List t = SetList(appstr, index); return t; } private static List SetList(string appendstr, int index) where T : new() { List t = new List(); try { var properties = new T().GetType().GetProperties(); var subNum = System.Web.HttpContext.Current.Request[appendstr + properties[index].Name].Split(',').Length; for (int i = 0; i < subNum; i++) { var r = properties; var model = new T(); foreach (var p in properties) { string pval = System.Web.HttpContext.Current.Request[appendstr + p.Name + ""]; if (!string.IsNullOrEmpty(pval)) { pval = pval.Split(',')[i]; string pptypeName = p.PropertyType.Name; p.SetValue(model, Convert.ChangeType(pval, p.PropertyType), null); } } t.Add(model); } } catch (Exception ex) { throw ex; } return t; } } }
相关内容
- ASP.NET中实现根据匿名类、datatable、sql生成实体类_实用技巧_
- ASP.NET中实现Form表单字段值自动填充到操作模型中_实用技巧_
- ASP.NET检测到不安全 Request.Form 值解决方案汇总_实用技巧_
- asp.net开发微信公众平台之验证消息的真实性_实用技巧_
- asp.net开发微信公众平台之获取用户消息并处理_实用技巧_
- ASP.NET中CKEditor与CKFinder的配置使用_实用技巧_
- javascript操作ASP.NET服务器控件_实用技巧_
- C#将DataTable转化为List<T>_实用技巧_
- 使用SWFUpload实现无刷新上传图片_实用技巧_
- 使用Lucene.NET实现站内搜索_实用技巧_
