我們知道ASP.NET MVC有個強大的地方就是Form表單提交到action的時候,可以直接將Form的參數直接裝配到action的參數實體對象中
比如
代碼如下:
action方法 Register(UserModel userModel)
{
.............................
}
在提交表單的時候,會自動講表單里面的字段封裝到對應的UserModel字段里面
那么 WebForm里面可不可以也紫將呢?
因為每次都要去獲得數據,優秀的程序員應該要學會代碼封裝,代碼復用,重復的工作不要做
我們其實可以利用反射來實例化對象的(自動裝配)
好了廢話不多....
pageload里面很簡單了
代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPost())
{
InitPage();//第一次訪問呈現頁面
}
else
{
UserModel userModel = AssembleModel<UserModel>(base.valueCollection);
}
}
關鍵就是基類里面的AssembleModel 方法了
基類里面
我們首先獲取到上下文的參數 IT404
代碼如下:
protected NameValueCollection valueCollection = HttpContext.Current.Request.Params;
基類很簡單,就是將上下文的提交的參數存放到valueCollection
然后再看AssembleModel方法了,這是一個泛型方法
代碼如下:
/// <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);
新聞熱點
疑難解答
圖片精選