62,047
社区成员
发帖
与我相关
我的任务
分享
//由form获取实体
public static T GetFormValue<T>(HttpRequest reqeust)
{
Type modelType = typeof(T);
T model = Activator.CreateInstance<T>();
foreach (string key in reqeust.Form.AllKeys)
{
foreach (PropertyInfo pi in modelType.GetProperties())
{
if (pi.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase))
{
string value = reqeust.Form[key];
pi.SetValue(model, HackType(value, pi.PropertyType), null);
}
}
}
return model;
}
//类型转换(网上找的。)
private static object HackType(object value, Type conversionType)
{
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
return null;
System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
}
return Convert.ChangeType(value, conversionType);
}
case InputType.Password:
if (value != null) {
tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
}
break;
<input type="text" name="Title" value="<%=article.Title %>"> ???
public static T GetFormValue<T>(HttpRequest reqeust)
{
Type modelType = typeof(T);
T model = Activator.CreateInstance<T>();
foreach (PropertyInfo pi in modelType.GetProperties())
{
if(reqeust.Form[pi.Name]!=null)
{
string value = reqeust.Form[key];
pi.SetValue(model, HackType(value, pi.PropertyType), null);
}
}
return model;
}
<!--表单元素的name和实体属性相同 -->
<form id="form1" action="TestSubmitForm.aspx" method="post">
<input name="subFlag" name="subFlag" type="hidden" value="1" />
<input name="Title" type="text" /><br />
<input name="Content" type="text" /><br />
<input name="Author" type="text" /><br />
<input name="Button1" type="submit" value="button" />
</form>