简体   繁体   中英

How to call javascript from code behind for Repeater control

There is a span element that need to load data dynamically from a Repeater control. The problem that I encounter is only first span element can display the value. The subsequent will display blank.

I've simplify the code behind as below.

    private int incre = 0;
    protected void Page_Load(object sender, EventArgs e)
    {


        foreach (RepeaterItem ritem in FeaturedRepeater.Items)
        {

            HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
            span.Load += new EventHandler(test);
        }

    }
    protected void test(object sender, EventArgs e)
    {

        HtmlGenericControl span = (HtmlGenericControl)sender;
        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
        incre++;
    }

Javascript function in .aspx file example as below:

    function timer(increment, timespan) {
       var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
       document.getElementById(id).innerHTML = id;   
    }

HTML part:

    <asp:Repeater runat="server" ID="FeaturedRepeater"       OnItemDataBound="FeaturedRepeater_ItemDataBound">
            <ItemTemplate>
                <span id='countdown' runat="server"></span>
            </ItemTemplate>
    </asp:Repeater>
Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);

you can't register the same key more then one time. that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work

btw

and ; after every javascript function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM