0

我有一个带有gridview 的asp.net 页面,它以编程方式(sp?)添加它的列。其中之一是 itemtemplate,它需要页面中的一些 javascript 才能运行。

模板本身有什么方法可以将所需的脚本添加到包含页面中 - 显然只是一次,即使认为模板实际上会为网格的每一行输出多次

这是在动态生成网格 cols 时添加到网格这里是生成 cols 的代码

sub GenerateCols
.....
        Dim tActions = New TemplateField()
        tActions.HeaderText = "Actions"
        tActions.ItemTemplate = New CheckBoxActionTemplate()
        grd.Columns.Add(tActions)
....
 end sub 

这是模板代码

   public class CheckBoxActionTemplate : ITemplate
    {
        public CheckBoxActionTemplate() { }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            HtmlAnchor aAll = new HtmlAnchor();
            aAll.InnerText = "all";
            aAll.Attributes.Add("class", "all");

            HtmlAnchor aNone = new HtmlAnchor();
            aNone.InnerText = "none";
            aNone.Attributes.Add("class", "none");

            HtmlAnchor aInvert = new HtmlAnchor();
            aInvert.InnerText = "invert";
            aInvert.Attributes.Add("class", "invert");

            container.Controls.Add(aAll);
            container.Controls.Add(aNone);
            container.Controls.Add(aInvert);
        }

        #endregion
    }

这是支持的javascript

 $("a.all").click( function() {
        $(this).closest('tr').find(':checkbox').each(function(){
            $(this).attr('checked', 'checked');
        });
        return false;
    });

// Select none
    $("a.none").click( function() {
        $(this).closest('tr').find(':checkbox').each(function(){
            $(this).removeAttr('checked');
        });
        return false;
    });


// Invert selection
    $("a.invert").click( function() {
        $(this).closest('tr').find(':checkbox').each(function(){
            if($(this).is(':checked')){
                $(this).removeAttr('checked');            
            }else{
               $(this).attr('checked', 'checked');
            }
        });
        return false;
    });

除此之外,如果它是一个多次出现在包含页面中的控件,该控件是否也可以将其 JS 添加到父页面本身,再次只是一次..?

4

1 回答 1

0

例如,您可以将脚本添加到 gridview 加载事件的页面中

<asp:GridView ID="GridView1" runat="server" onload="GridView1_Load">
    </asp:GridView>

然后处理事件并编写脚本

protected void GridView1_Load(object sender, EventArgs e)
    {
        StringBuilder strScript = new StringBuilder();
        strScript.Append("<script language=JavaScript>");
        strScript.Append("$('a.all').click( function() {});//etc etc</script>");
        ClientScript.RegisterClientScriptBlock(this.GetType(), "Pop", strScript.ToString());
    }
于 2013-02-15T19:01:22.067 回答