控制器中,每次为实体赋值都需要接收参数,重复操作很多,因此有这个思路来为实体自动赋值。
建一个基础控制器,让其他控制器继承,用来完成一下基础的操作。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using Util;
namespace Manweb.Controllers
{
public class BaseController : Controller
{
protected string GetParam(string key)
{
if (Request.Form[key] != null)
{
return Request.Form[key];
}
else
{
throw new Exception(string.Format("需要参数:{0}", key));
}
}
protected T GetEntity<T>()
{
Type type = typeof(T);
T info = Activator.CreateInstance<T>();
foreach (PropertyInfo mi in type.GetProperties())
{
if (!mi.IsDefined(typeof(NoWriteAttribute)))
{
object value = new object();
bool needset = true;
try
{
string v = GetParam(mi.Name);
if (typeof(System.Enum).IsAssignableFrom(mi.PropertyType))
{
value = Enum.Parse(mi.PropertyType, v);
}
else
{
value = Convert.ChangeType(v, mi.PropertyType);
}
}
catch (Exception e)
{
if (mi.Name.ToLower() != "id")
{
if (!e.Message.Contains("需要参数"))
{
throw e;
}
}
else
{
needset = false;
}
}
if (needset)
{
mi.SetValue(info, value);
}
}
}
return info;
}
}
}
控制器中使用:
public JsonResult AddServer()
{
return Common.ActFuncJson(() =>
{
Server info = base.GetEntity<Server>();
new ServerImpl().Add(info);
});
}
再来一个拷贝实体的方法:
/// <summary>
/// 复制两个实例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">源实例</param>
/// <param name="target">目标实例</param>
/// <param name="removeField">不需要复制的字段</param>
/// <returns></returns>
public static void CopyTo<T>(T source, T target, List<string> removeField)
{
Type type = typeof(T);
foreach (PropertyInfo mi in type.GetProperties())
{
if (removeField.Find(s => s.ToLower() == mi.Name.ToLower()) == null)
{
mi.SetValue(target, mi.GetValue(source));
}
}
}
控制器修改实体的方法:
public JsonResult UpdateServer()
{
return Common.ActFuncJson(() =>
{
ServerImpl impl = new Dal.Customer.ServerImpl();
Server info = impl.Get(GetParam("id"));
if (info == null)
{
throw new ExceptionCustom();
}
else
{
Server tmp = base.GetEntity<Server>();
Common.CopyTo<Server>(tmp, info, new List<string>() { "id" });
impl.Update(info);
}
});
}
这样操作,添加和修改实体对象的代码就少很多了,不过要求接收的参数名字与类属性名相同才可以。