国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net實現非常實用的自定義頁面基類(附源碼)

2024-07-10 12:47:31
字體:
來源:轉載
供稿:網友

本文實例講述了asp.net實現非常實用的自定義頁面基類。,具體如下:

看到前面幾篇文章(如:《asp.net實現利用反射,泛型,靜態方法快速獲取表單值到Model的方法》)想到的。下面總結發布一個筆者在開發中常用的一個自定義BasePage類,廢話不多說了,直接貼代碼。

一、BasePage類

1、代碼

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Reflection;namespace DotNet.Common.WebForm{ using DotNet.Common.Model; using DotNet.Common.Util; public class BasePage : System.Web.UI.Page {  public BasePage()  {  }  protected override void OnInit(EventArgs e)  {   base.OnInit(e);   //CancelFormControlEnterKey(this.Page.Form.Controls); //取消頁面文本框的enter key  }  #region 取消頁面文本控件的enter key功能  /// <summary>  /// 在這里我們給Form中的服務器控件添加客戶端onkeydown腳步事件,防止服務器控件按下enter鍵直接回發  /// </summary>  /// <param name="controls"></param>  public virtual void CancelFormControlEnterKey(ControlCollection controls)  {   //向頁面注冊腳本 用來取消input的enter key功能   RegisterUndoEnterKeyScript();   foreach (Control item in controls)   {    //服務器TextBox    if (item.GetType() == typeof(System.Web.UI.WebControls.TextBox))    {     WebControl webControl = item as WebControl;     webControl.Attributes.Add("onkeydown", "return forbidInputKeyDown(event)");    }    //html控件    else if (item.GetType() == typeof(System.Web.UI.HtmlControls.HtmlInputText))    {     HtmlInputControl htmlControl = item as HtmlInputControl;     htmlControl.Attributes.Add("onkeydown", "return forbidInputKeyDown(event)");    }    //用戶控件    else if (item is System.Web.UI.UserControl)    {     CancelFormControlEnterKey(item.Controls); //遞歸調用    }   }  }  /// <summary>  /// 向頁面注冊forbidInputKeyDown腳本  /// </summary>  private void RegisterUndoEnterKeyScript()  {   string js = string.Empty;   System.Text.StringBuilder sb = new System.Text.StringBuilder();   sb.Append("function forbidInputKeyDown(ev) {");   sb.Append(" if (typeof (ev) != /"undefined/") {");   sb.Append(" if (ev.keyCode || ev.which) {");   sb.Append(" if (ev.keyCode == 13 || ev.which == 13) { return false; }");   sb.Append(" } } }");   js = sb.ToString();   if (!this.Page.ClientScript.IsClientScriptBlockRegistered("forbidInput2KeyDown"))    this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "forbidInput2KeyDown", js, true);  }  #endregion  #region 利用反射取/賦頁面控件的值  /// <summary>  /// 從頁面中取控件值,并給對象賦值  /// </summary>  /// <param name="dataType">要被賦值的對象類型</param>  /// <returns></returns>  public virtual BaseObj GetFormData(Type dataType)  {   BaseObj data = (BaseObj)Activator.CreateInstance(dataType);//實例化一個類   Type pgType = this.GetType(); //標識當前頁面   BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic;//反射標識   PropertyInfo[] propInfos = data.GetType().GetProperties();//取出所有公共屬性    foreach (PropertyInfo item in propInfos)   {    FieldInfo fiPage = pgType.GetField(item.Name, bf);//從頁面中取出滿足某一個屬性的字段    if (fiPage != null) //頁面的字段不為空,代表存在一個實例化的控件類    {     object value = null;     Control pgControl = (Control)fiPage.GetValue(this); //根據屬性,找到頁面對應控件,這要求頁面控件命名必須和對象的屬性一一對應相同     //下面取值     Type controlType = pgControl.GetType();     if (controlType == typeof(Label))     {      value = ((Label)pgControl).Text.Trim();     }     else if (controlType == typeof(TextBox))     {      value = ((TextBox)pgControl).Text.Trim();     }     else if (controlType == typeof(HtmlInputText))     {      value = ((HtmlInputText)pgControl).Value.Trim();     }     else if (controlType == typeof(HiddenField))     {      value = ((HiddenField)pgControl).Value.Trim();     }     else if (controlType == typeof(CheckBox))     {      value = (((CheckBox)pgControl).Checked);//復選框     }     else if (controlType == typeof(DropDownList))//下拉框     {      value = ((DropDownList)pgControl).SelectedValue;     }     else if (controlType == typeof(RadioButtonList))//單選框列表     {      value = ((RadioButtonList)pgControl).SelectedValue;      if (value != null)      {       if (value.ToString().ToUpper() != "TRUE" && value.ToString().ToUpper() != "FALSE")        value = value.ToString() == "1" ? true : false;      }     }     else if (controlType == typeof(Image)) //圖片     {      value = ((Image)pgControl).ImageUrl;     }     try     {      object realValue = null;      if (item.PropertyType.Equals(typeof(Nullable<DateTime>))) //泛型可空類型       {       if (value != null)       {        if (string.IsNullOrEmpty(value.ToString()))        {         realValue = null;        }        else        {         realValue = DateTime.Parse(value.ToString());        }       }      }      else if (item.PropertyType.Equals(typeof(Nullable))) //可空類型       {       realValue = value;      }      else      {       try       {        realValue = Convert.ChangeType(value, item.PropertyType);       }       catch       {        realValue = null;       }      }      item.SetValue(data, realValue, null);     }     catch (FormatException fex)     {      DotNet.Common.Util.Logger.WriteFileLog(fex.Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");      throw fex;     }     catch (Exception ex)     {      DotNet.Common.Util.Logger.WriteFileLog(ex.Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");      throw ex;     }    }   }   return data;  }  /// <summary>  /// 通過對象的屬性值,給頁面控件賦值  /// </summary>  /// <param name="data"></param>  public virtual void SetFormData(BaseObj data)  {   Type pgType = this.GetType();   BindingFlags bf = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static;   PropertyInfo[] propInfos = data.GetType().GetProperties();   foreach (PropertyInfo item in propInfos)   {    FieldInfo myField = pgType.GetField(item.Name, bf);    if (myField != null)    {     Control myControl = (Control)myField.GetValue(this); //根據屬性名取到頁面控件     object value = item.GetValue(data, null); //取對象的屬性值     Type propType = item.PropertyType;     if (value != null)     {      Type valueType = value.GetType();      try      {       Type controlType = myControl.GetType();       if (controlType == typeof(Label))       {        if (valueType == typeof(DateTime))        {         ((Label)myControl).Text = (Convert.ToDateTime(value)).ToShortDateString();        }        else        {         ((Label)myControl).Text = value.ToString();        }       }       else if (controlType == typeof(TextBox))       {        if (valueType == typeof(DateTime))        {         ((TextBox)myControl).Text = (Convert.ToDateTime(value)).ToShortDateString();        }        else        {         ((TextBox)myControl).Text = value.ToString();        }       }       else if (controlType == typeof(HtmlInputText))       {        if (valueType == typeof(DateTime))        {         ((HtmlInputText)myControl).Value = (Convert.ToDateTime(value)).ToShortDateString();        }        else        {         ((HtmlInputText)myControl).Value = value.ToString();        }       }       else if (controlType == typeof(HiddenField))       {        ((HiddenField)myControl).Value = value.ToString();       }       else if (controlType == typeof(CheckBox))       {        if (valueType == typeof(Boolean)) //布爾型        {         if (value.ToString().ToUpper() == "TRUE")          ((CheckBox)myControl).Checked = true;         else          ((CheckBox)myControl).Checked = false;        }        else if (valueType == typeof(Int32)) //整型 (正常情況下,1標識選擇,0標識不選)        {         ((CheckBox)myControl).Checked = string.Compare(value.ToString(), "1") == 0;        }       }       else if (controlType == typeof(DropDownList))       {        try        {         ((DropDownList)myControl).SelectedValue = value.ToString();        }        catch        {         ((DropDownList)myControl).SelectedIndex = -1;        }       }       else if (controlType == typeof(RadioButton))       {        if (valueType == typeof(Boolean)) //布爾型        {         if (value.ToString().ToUpper() == "TRUE")          ((RadioButton)myControl).Checked = true;         else          ((RadioButton)myControl).Checked = false;        }        else if (valueType == typeof(Int32)) //整型 (正常情況下,1標識選擇,0標識不選)        {         ((RadioButton)myControl).Checked = string.Compare(value.ToString(), "1") == 0;        }       }       else if (controlType == typeof(RadioButtonList))       {        try        {         if (valueType == typeof(Boolean)) //布爾型         {          if (value.ToString().ToUpper() == "TRUE")           ((RadioButtonList)myControl).SelectedValue = "1";          else           ((RadioButtonList)myControl).SelectedValue = "0";         }         else          ((RadioButtonList)myControl).SelectedValue = value.ToString();        }        catch        {         ((RadioButtonList)myControl).SelectedIndex = -1;        }       }       else if (controlType == typeof(Image))       {        ((Image)myControl).ImageUrl = value.ToString();       }      }      catch (FormatException fex)      {       DotNet.Common.Util.Logger.WriteFileLog(fex.Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");      }      catch (Exception ex)      {       DotNet.Common.Util.Logger.WriteFileLog(ex.Message, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");      }     }    }   }  }  #endregion  #region 日志處理  /// <summary>  /// 出錯處理:寫日志,導航到公共出錯頁面  /// </summary>  /// <param name="e"></param>  protected override void OnError(EventArgs e)  {   Exception ex = this.Server.GetLastError();   string error = this.DealException(ex);   DotNet.Common.Util.Logger.WriteFileLog(error, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");   if (ex.InnerException != null)   {    error = this.DealException(ex);    DotNet.Common.Util.Logger.WriteFileLog(error, HttpContext.Current.Request.PhysicalApplicationPath + "LogFile");   }   this.Server.ClearError();   this.Response.Redirect("/Error.aspx");  }  /// <summary>  /// 處理異常,用來將主要異常信息寫入文本日志  /// </summary>  /// <param name="ex"></param>  /// <returns></returns>  private string DealException(Exception ex)  {   this.Application["StackTrace"] = ex.StackTrace;   this.Application["MessageError"] = ex.Message;   this.Application["SourceError"] = ex.Source;   this.Application["TargetSite"] = ex.TargetSite.ToString();   string error = string.Format("URl:{0}/n引發異常的方法:{1}/n錯誤信息:{2}/n錯誤堆棧:{3}/n",    this.Request.RawUrl, ex.TargetSite, ex.Message, ex.StackTrace);   return error;  }  #endregion }}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南安市| 万安县| 牡丹江市| 师宗县| 民丰县| 珲春市| 玉田县| 镇赉县| 绥中县| 宜君县| 蓬溪县| 讷河市| 女性| 会昌县| 德令哈市| 栖霞市| 罗平县| 华蓥市| 西和县| 准格尔旗| 古交市| 库伦旗| 竹山县| 墨江| 定日县| 庆城县| 元阳县| 沅陵县| 临安市| 西乌| 玉林市| 延寿县| 德钦县| 大连市| 临沭县| 台江县| 六盘水市| 揭东县| 伊宁县| 名山县| 松滋市|