ASP. NET uses conditional expressions when binding
ASP. net2.0 does not support conditional expressions during data binding. Asp.net 4.0 has solved this problem smoothly without modifying the code.
Let's take a look at a simple ASP. NET data binding scenario with such a repeater:
1: <asp:Repeater runat="server" ID="itemsList">
2: <HeaderTemplate>
3: <table border="1" cellspacing="0" cellpadding="5">
4: </HeaderTemplate>
5: <ItemTemplate>
6: <tr>
7: <td align="right">
8: <%# Container.ItemIndex + 1 %>.
9: </td>
10: <td>
11: <%# eval_r("Title") %>
12: </td>
13: </tr>
14: </ItemTemplate>
15: <FooterTemplate>
16: </table>
17: </FooterTemplate>
18: </asp:Repeater>
Then the backend Cs:
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: var items = new[] {
4: new { Id = 1, Title = "Headline 1" },
5: new { Id = 2, Title = "Headline 2" },
6: new { Id = 2, Title = "Headline 3" },
7: new { Id = 2, Title = "Headline 4" },
8: new { Id = 2, Title = "Headline 5" }
9: };
10: itemsList.DataSource = items;
11: itemsList.DataBind();
12: }
When we need to determine the data row when binding, we need to create a similar method or function:
1: /// <summary>
2: /// Iifs the specified condition.
3: /// </summary>
4: /// <param name="condition">if set to <c>true</c> [condition].</param>
5: /// <param name="trueResult">The true result.</param>
6: /// <param name="falseResult">The false result.</param>
7: /// <returns></returns>
8: protected object Iif(bool condition, object trueResult, object falseResult)
9: {
10: return condition ? trueResult : falseResult;
11: }
Then use it in aspx:
1: <asp:Repeater runat="server" ID="Repeater1">
2: <HeaderTemplate>
3: <table border="1" cellspacing="0" cellpadding="5">
4: </HeaderTemplate>
5: <ItemTemplate>
6: <tr style='background-color: <%# Iif(Container.ItemIndex % 2==0, "white", "whitesmoke") %>'>
7: <td align="right">
8: <%# Container.ItemIndex + 1 %>.</td>
9: <td>
10: <%# eval_r("Title") %></td>
11: </tr>
12: </ItemTemplate>
13: <FooterTemplate>
14: </table>
15: </FooterTemplate>
16: </asp:Repeater>
This is imitating the IIF function in VB. In ASP. NET 4.0, we can write this directly:
1: <asp:Repeater runat="server" ID="Repeater2">
2: <HeaderTemplate>
3: <table border="1" cellspacing="0" cellpadding="5">
4: </HeaderTemplate>
5: <ItemTemplate>
6: <tr style='background-color:<%# Container.ItemIndex % 2==0 ? "white" : "whitesmoke" %>'>
7: <td align="right">
8: <%# Container.ItemIndex + 1 %>.</td>
9: <td>
10: <%# eval_r("Title") %></td>
11: </tr>
12: </ItemTemplate>
13: <FooterTemplate>
14: </table>
15: </FooterTemplate>
16: </asp:Repeater>
Http://blog.sina.com.cn/s/blog_3e29b20b0100il16.html