Search code examples
asp.netrazorwebformsaspx-user-control

Using c# in Web Forms to passing parameter to user control


From an aspx page, I am trying to display a user control for each item in a collection, but the C# seems to be ignored when tryign to set the UserControl parameter:

<%foreach (Fetus item in this.pregnancy.Fetus) {%>
    //this returns a GUID:
    "<%= item.Id.ToString() %>" 

    //this does not work, returns the characters between "" like < %= item.Id.ToString()%>:
    <uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId="<%= item.Id.ToString()%>" />
<% } %>

I would expect this to work, what's wrong?


Solution

  • You have to use a data binding expression

    <uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# item.Id.ToString()%>' />
    

    But you have to call DataBind() in code behind for that to work.

    You can also use a Repeater

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# Eval("id").ToString()%>' />
        </ItemTemplate>
    </asp:Repeater>
    

    And then bind data to it in code behind

    Repeater1.DataSource = pregnancy.Fetus;
    Repeater1.DataBind();