【问题标题】:Working with Dynamic User Controls使用动态用户控件
【发布时间】:2016-06-03 13:07:05
【问题描述】:

我有一个自定义用户控件,其中包含有关我以编程方式添加到页面的人员的信息。为简单起见,假设我的用户控件只保存一个人的名字和姓氏。

<table>
  <tr>
    <td>
      <asp:Label ID="lblFirstName" runat="server">First Name</asp:Label>
    </td>
    <td>
      <asp:TextBox ID="txtFirstName" runat="server" />
    </td>
  </tr>
  <tr>
    <td>
        <asp:Label ID="lblLastName" runat="server">Last Name</asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txtLastName" runat="server" />
    </td>
  </tr>
</table>

我需要允许用户添加参加活动的人,并且他们需要能够添加尽可能多的人。我在屏幕上有一个“添加人员”按钮,因此当用户选择该按钮时,页面中会添加一个空白用户控件供他们填写。在后面的代码中,我跟踪有多少人参加,以便我可以使用此列表在回发时呈现用户控件。

public List<Person> AttendingPeople
{
    get { return ViewState["AttendingPeople"] == null ? new List<Person>() : ViewState["AttendingPeople"] as List<Person>; }
    set { ViewState["AttendingPeople"] = value; }
}

填写完所有参会人员的信息后,用户需要保存信息。当他们选择保存时,我需要验证是否已填写所有文本框。我更喜欢使用 javascript 来执行此操作,但是,我不知道如何定位信息,因为我无法确定页面上加载了多少用户控件。到目前为止,这就是我所拥有的。

function ValidateSave() {
    if ('<%= this.AttendingPeople.Count %>' == 0) {
        alert('Need to fill out at least one person whose attending.');
    }
    else {
        //Where user controls are added.
        var children = document.getElementById('<%= divAttending.ClientID %>').children;  
        for (var i = 0; i < children.length; i++) {

            //Find table inside user control that holds data
            if (children[i].tagName == 'TABLE') {
                var table = children[i];
                var rows = table.rows;
                for (var r = 0; r < rows.length; r++) {
                    var row = rows[r];
                    //Not sure how to extract data from each row
                }
            }   
        }
    }
}

我的第一个问题是'&lt;%= this.AttendingPeople.Count %&gt;' 总是返回列表中的初始计数。在 Page_Load 中,如果我将 3 人添加到列表中,那么计数将始终为 3。如果我不添加任何内容,那么无论我随着时间的推移添加多少人,计数将始终为 0。

其次,我严重怀疑我是否会以正确的方式查找所有数据。我将不胜感激任何建议或批评。我对 ASP.NET 了解不多,所以我知道我有很多东西要学。提前致谢。

【问题讨论】:

    标签: javascript asp.net user-controls


    【解决方案1】:
    <%= this.AttendingPeople.Count %>
    

    此代码仅在视图呈现后打印参加人员的初始计数。你可以在你的页面源代码中检查它。

    要获得实际参加人数,您可以存储初始值,并在每次添加或删除人员时增加或减少它。类似的东西:

    var apcount = '<%= this.AttendingPeople.Count %>';
    
    /* do it when you add a person */
    apcount++;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2017-01-06
      相关资源
      最近更新 更多