Asp.net 基礎4(自訂控制項的使用之用戶端指令碼產生)

來源:互聯網
上載者:User
在自訂控制項時,會比較常見的有寫用戶端的指令碼。也就是在重寫Control的Render方法時,可以直接輸出用戶端的指令碼。但是這樣有兩點不好的地方,1,在產生多個使用者控制項的執行個體是,會產生多個指令碼,造成指令碼之間調用的混淆2,在一個控制項呼叫指令碼,會在另一個指令檔中葉調用。產生差異。下面的這個方法是最好的方法:編寫了一個類似於下棋的控制項,代碼using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OwnControl
{
    public class ChessControl:Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "5px");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "5px");
            for (int row = 0; row < 3; row++)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                for (int col = 0; col < 3; col++)
                {
                    string clk = string.Format(
                        "OnClickCell(this,'{0}')", ClientID);
                    writer.AddAttribute(HtmlTextWriterAttribute.Border, "5px");
                    writer.AddAttribute(HtmlTextWriterAttribute.Width, "20px");
                    writer.AddAttribute(HtmlTextWriterAttribute.Onclick, clk);
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    writer.Write("&nbsp;");
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }

        protected override void OnInit(EventArgs e)
        {
            string sCode ="<script language=javascript> var g_grWentLast=new Object(); function OnClickCell(cell,idx) { if(cell.innerText==\" \"){ if(g_grWentLast[idx]) cell.innerText='O'; else cell.innerText='X'; g_grWentLast[idx]=!g_grWentLast[idx]; } else cell.innerText=' ';}; </script>";
            //
            //由於此方法使用鍵來識別指令碼塊,
            //所以不需要在每次不同的伺服器控制項執行個體請求指令碼塊時都向輸出資料流發出指令碼塊。
            //使用鍵還可以降低不同控制項的指令碼塊相互幹擾的可能性。
            Page.RegisterClientScriptBlock("CellCode", sCode);
        }
    }
}

 

 

 介面的使用:

<useown:ChessControl ID="user3" runat="server"></useown:ChessControl>

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.