很好用的request轉換為實體方法還有判斷實體所有引數不能為空的方法

時間都瘋了,你知道嗎?發表於2016-07-22

/// <summary>
/// 模型輔助處理類
/// 2016-04-18
/// </summary>
public class ModelHelper
{
/// <summary>
/// 將資料轉化為模型
/// 2016-04-18 基礎資料型別:Int32,decimal
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public static void ConvertToModel<T>(ref T t)
{
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
Type[] tempArr = new Type[] {typeof(Int32),typeof(decimal)};
object tempObject = null;
for (Int32 i = 0; i < properties.Length; i++)
{
if (ReqUtils.FormString(properties[i].Name) != null || properties[i].PropertyType.Name.ToLower() == "httpfilecollection")
{
switch (properties[i].PropertyType.Name.ToLower())
{
case "int32": tempObject = Int32.Parse(string.Format("0{0}", ReqUtils.FormString(properties[i].Name))); break;
case "decimal": tempObject = decimal.Parse(string.Format("0{0}", ReqUtils.FormString(properties[i].Name))); break;
case "httpfilecollection": tempObject = System.Web.HttpContext.Current.Request.Files; break;
default:
tempObject = string.Format("{0}", ReqUtils.FormString(properties[i].Name));
break;
}
properties[i].SetValue(t, tempObject, null);
}
}
}
/// <summary>
/// 該實體是否都為空
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public bool ModelIsNotNull(object model)
{
bool istrue = true;
Type type = model.GetType();
var flags = GetOnlyProperty();
var list = type.GetProperties(flags).ToList();
foreach (var p in list)
{
if (IsColumn(p))
{
object value = p.GetValue(model, null) ?? "";
if (string.IsNullOrWhiteSpace(value.ToString()))
{
istrue = false;
break;
}
}
}
return istrue;
}
private BindingFlags GetOnlyProperty()
{
return BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
}
private bool IsColumn(PropertyInfo info)
{
object[] objs = info.GetCustomAttributes(typeof(Attribute), true);
return objs.Length == 0;
}
/// <summary>
/// 獲取操作提示翻譯
/// </summary>
/// <param name="key"></param>
/// <param name="lan"></param>
/// <returns></returns>
public static string GetTans(string key, string lan = "")
{
try
{
if (string.IsNullOrWhiteSpace(lan))
{
lan = "cn";
}
if (lan.ToLower().Contains("cn") || lan.ToLower().Contains("zh"))
{
lan = "zh";
}
string className = "PageInfo_" + lan;
var globalResourceObject = HttpContext.GetGlobalResourceObject(className, key);
if (globalResourceObject != null)
return globalResourceObject.ToString() == "" ? key : globalResourceObject.ToString();
else
{
return key;
}
}
catch
{
return key;
}
}
}

相關文章