【问题标题】:Dynamic Button not triggered in ASP.Net from static class静态类在 ASP.Net 中未触发动态按钮
【发布时间】:2016-04-13 05:25:35
【问题描述】:

我正在尝试制作一个包含几行的动态表,最后一行是一个加号按钮,它将添加一个新行。 (为了简单起见,我只描述重要信息。)

我想到了这样的方式来完成它:

// .aspx code 
<li><asp:LinkButton ID="LM_Show" runat="server" Text="Show list" OnClick="Action"/></li>
<asp:PlaceHolder ID="infoTable" runat="server"></asp:PlaceHolder>

//CreateTable function
public void Clicked(object sender, EventArgs e){
    table();
}
public void table() {
    //Do stuff...

    //Screen variable is keeping track of which screen should be shown in .aspx
    infoTable.Controls.Add(CreateView.createTable<Employee>(screen, this.Context, table));
}

//Create the actual table 
public static Table createTable<T>(Screen screen, HttpContext context, Action method) where T : new() {
    //New table and make it stretch
    Table tb = new Table();
    tb.Width = Unit.Percentage(100);
    tb.Height = Unit.Percentage(100);

    //Gather list from session
    List<T> items = (List<T>)context.Session["list"];

    //Create table content based on the list
    for (int i = 1; i <= items.Count(); i++) {
        TableRow tr = new TableRow();

       //Foreach property create cells with content according to the property
       //Add these cells to the row

        tb.Rows.Add(tr);
    }

    //Create 1 final row which has a button to be able to add 1 row
    TableRow tr2 = new TableRow();
    TableCell tc = new TableCell();
    tr.Cells.Add(tc);

    //Create the Button
    Button button = new Button();
    button.Text = "+";

    //!!This is not getting triggered!!//
    button.Click += (s, e) => { 
        List<T> tempItems = (List<T>)context.Session["list"]; 
        tempItems.Add(new T()); 
        context.Session["list"] = tempItems; 
        //When a button is pressed, it gives a postback.
        //The table has to be rebuild over again with the newly added item
        method(); 
    };
    //!!This is not getting triggered!!//

    //Add the button
    tr2.Cells[0].Controls.Add(button);
    tb.Rows.Add(tr2);

    return tb;
}

任何关于代码或如何更好地完成它的 cmet 也非常欢迎。

【问题讨论】:

    标签: c# asp.net dynamic


    【解决方案1】:

    如果您使用 jQuery AJAX 并与 Web 服务/方法进行通信以获取数据,则可以更轻松地实现这一点。但是,它也可以在 C# 中实现。假设下面给出的部分代码不起作用,

    //Add the button
    tr2.Cells[0].Controls.Add(button);
    tb.Rows.Add(tr2);
    

    您可以尝试先将button 添加到tc,然后将tc 添加到tr 行中

    tc.Controls.Add(button);
    tr2.Cells.Add(tc);
    tb.Rows.Add(tr2);
    

    祝你好运!

    【讨论】:

    • 感谢您的帮助!但是按钮正在显示。那不是问题。它只是不会触发我传递的方法! :-(
    • 你是说重绘表格的方法吧? method();
    • 另外,你是如何添加新项目的?当你点击按钮时究竟会发生什么?它是在您通过键入内容添加项目的位置添加一个新行,还是向用户提供一个弹出窗口,他/她可以在其中添加新项目?
    • 对不起,我想把它写成简短的。编辑了函数名称。现在您应该看到我要调用的内容了。
    猜你喜欢
    • 1970-01-01
    • 2017-06-28
    • 2010-12-19
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 2020-12-28
    相关资源
    最近更新 更多