<%if statement%>中设置td文本的函数总是被调用

问题描述 投票:0回答:1

我想使用C#函数在dataRepeater中设置文本并在aspx页面中使用if语句。

<asp:Repeater ID="dataRepeater" runat="server">
     <ItemTemplate>
         <tr>
           <%if (condition){ %>
              <td>
                  <%#FunctionName(DataBinder.Eval(Container.DataItem, ""))%>
              </td>
         <tr>
     </ItemTemplate>
</asp:Repeater>
//.cs
protected string FunctionName(){
//
//
//

return string

}

但是,任何条件总是调用 C# 函数,这是正常情况还是我在这里做错了什么,谢谢。

c# html asp.net webforms
1个回答
0
投票
**ASPX :**

    <asp:Repeater ID="dataRepeater" runat="server" OnItemDataBound="dataRepeater_ItemDataBound">
        <ItemTemplate>
            <tr>
                <td id="myCell" runat="server">
                    <!-- Initially, you can set an empty text here or a placeholder -->
                </td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>


**(.cs file):**

protected void Page_Load(object sender, EventArgs e)
{
    // Bind data to the Repeater here
    dataRepeater.DataSource = yourDataSource; // Replace with your data source
    dataRepeater.DataBind();
}

protected void dataRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    // Check if the item is a data item (not the header or footer)
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        // Get the data item (e.g., some object, or DataBinder.Eval)
        var dataItem = e.Item.DataItem;
        
        // Get a reference to the <td> element
        var td = e.Item.FindControl("myCell") as HtmlTableCell;
        
        // Condition based on the dataItem or other logic
        if (YourCondition(dataItem))
        {
            // Call your C# function here
            td.InnerText = FunctionName(dataItem); // Modify the text content conditionally
        }
        else
        {
            td.InnerText = "Default Value"; // Or leave it empty, depending on your need
        }
    }
}

// Your C# function that returns the string you want to set
protected string FunctionName(object dataItem)
{
    // Perform your logic here
    return "Some Result"; // Return the desired value
}

// Example condition method
private bool YourCondition(object dataItem)
{
    // Replace with your actual condition logic
    return true; // Just an example; you should check dataItem here
}

避免将条件语句与数据绑定表达式混合以实现复杂的逻辑。相反,请在 C# 代码中处理此类逻辑,以获得更好的清晰度和可维护性。<%# %>

© www.soinside.com 2019 - 2024. All rights reserved.