擴展方法 之 Asp.Net篇

作者: CoolCode  來源: 博客園  發布時間: 2009-09-28 14:14  閱讀: 3293 次  推薦: 0   原文鏈接   [收藏]  

  說起擴展方法,不得不提博客園的鶴沖天,其關于擴展方法的文章基本上占了總文章的一半,其中不乏優秀之作。
  我在Asp.Net開發期間也總結了不少擴展方法,與大家分享一下。

  1. 獲取GridView的主鍵值:

public static T GetKey<T>(this GridView grid, int rowIndex)
{  
    T key = (T)grid.DataKeys[rowIndex].Value;
    return key;
}

示例:

protected void gvMaster_RowEditing(object sender, GridViewEditEventArgs e)
{
   string key = gvMaster.GetKey<string>(e.NewEditIndex);
}

  2. 獲取GridView的行號:

public static int GetRowIndex(this GridViewCommandEventArgs e)
{
    GridViewRow gvrow = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
    return gvrow.RowIndex;
}

示例:

protected  void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
 {
    int rowIndex = e.GetRowIndex();           
 }

  3. 查找指定ID的控件,并轉換成指定類型:

public static T FindControl<T>(this Control control, string id) where T : class
{
    Control c = control.FindControl(id);
    return  (c as T);
}

示例:

//從整個頁面里查找ID為lblTest的Label
this.FindControl("lblTest");
//從Panel里查找ID為lblTest的Label
Panel1.FindControl("lblTest");

  4. 查找指定類型的控件:

public static List<T> FindControls<T>(this Control control) where T : Control
{
        Action<Control, List<T>> findhelper =null;
        findhelper= (ctl, list) =>
        {
                 if (ctl is T)
                  {
                     list.Add((T)ctl);
                 }
                         if (ctl.HasControls())
                     {
                             foreach (Control c in ctl.Controls)
                             {
                                     findhelper(c, list);
                             }
                     }
         };
             List<T> controls =new List<T>();
             findhelper(control, controls);
             return controls;
}

示例:

//從整個頁面里查找所有Label
this.FindControls();
//從Panel里查找所有Label
Panel1.FindControls();

備注:
  在實際開發中有個不錯的應用場景——找到所有的RequiredFieldValidator控件并統一設置其錯誤信息和提示信息:

var rs = this.FindControls<RequiredFieldValidator>();
             foreach (var r in rs)
   {
                 r.ErrorMessage = "*";
                 r.ToolTip = "不能為空";
    }

  當然,如果在FindControls中增加一個Action 參數應該是個不錯的方案,這樣以上語句就可以直接寫成:

 var rs = this.FindControls<RequiredFieldValidator>(r => 
{
                 r.ErrorMessage = "*";
                 r.ToolTip = "不能為空";
  });

  5. 判斷本頁是是否使用Ajax (其實就是判斷是否使用了ScriptManager):

public static bool IsAjaxPage(this Page page)
          {
             return (ScriptManager.GetCurrent(page) != null);
         }
 
         public static bool IsAjaxPage(this Control control)
          {
             return (ScriptManager.GetCurrent(control.Page) != null);
         }

示例:

if (this.IsAjaxPage())
              {
                 do sth about ajax 
             }

6. UpdatePanel 調用javascript 顯示信息:

public static void Alert(this UpdatePanel panel, string message)
     {
               if (message.Length > 50)
            {
                message = message.Substring(0, 50);//最多顯示50個字符
             }
             //去除javascript不支持的字符
              message = Utility.ReplaceStrToScript(message);
      ScriptManager.RegisterClientScriptBlock(panel, panel.GetType(), "Message",
              string.Format( " alert('{0}'); ", message) , true);
       }

示例:

udpHeader.Alert("Hello,I'm Bruce!");//注:udpHeader 是UpdatePanel 類型

把 alert 換成漂亮的提示框就perfect了。

總結:
  實際項目中遠不止這幾個擴展方法,只是比較典型就發上來交流交流,其他的稍微有點復雜而且不經常用到。
  有了這些擴展方法,就可以去除項目中很多重復性代碼,歡迎大家提出更好的建議。
  末了發覺有點純代碼的味道,但實在這些方法都是入門級,也應該沒哪一個是看不懂的,也就不在這里一一羅嗦。

0
0
 
 
 

文章列表

全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()