我們知道ASP.NET MVC有個強大的地方就是Form表單提交到action的時候,可以直接將Form的參數(shù)直接裝配到action的參數(shù)實體對象中
action方法 Register(UserModel userModel)
{
.............................
}
好了廢話不多....
/// 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);
}
catch (Exception ex)
{
}
return props;
}
/// summary>
/// 根據(jù)NameValueCollection 自動裝配
/// /summary>
/// typeparam name="T">/typeparam>
/// param name="valueCollection">/param>
/// returns>/returns>
protected T AssembleModelT>(NameValueCollection valueCollection)
{
PropertyInfo[] propertyInfoList = GetPropertyInfoArray(typeof(T));
object obj = Activator.CreateInstance(typeof(T), null);//創(chuàng)建指定類型實例
foreach (string key in valueCollection.Keys)//所有上下文的值
{
foreach (var PropertyInfo in propertyInfoList)//所有實體屬性
{
if (key.ToLower() == PropertyInfo.Name.ToLower())
{
PropertyInfo.SetValue(obj, valueCollection[key], null);//給對象賦值
}
}
}
return (T)obj;
}