How to save the value of a data binding expression to a variable

I need to access the value of a related item several times in a template. Right now my ListView template looks like this:

<asp:ListView ID="ListView1" runat="server" ItemPlaceholderID="plc"><br/>
 <ItemTemplate><br/>
  <input type="radio" class="myrating<%# DataBinder.Eval(Container.DataItem, "Day")%>" value="3" /><br/>
  <input type="radio" class="myrating<%# DataBinder.Eval(Container.DataItem, "Day")%>" value="4" /><br/>
    </ItemTemplate><br/>
    <LayoutTemplate><br/>
        <div id="plc" runat="server"><br/>
        </div><br/>
    </LayoutTemplate><br/>
    <EmptyDataTemplate><br/>
        No data</EmptyDataTemplate><br/>
</asp:ListView><br/>

Under certain conditions, I can have dozens of switches, so calling again <%# DataBinder.Eval(Container.DataItem, "Day")%>seems inefficient.

I would like to assign the value of this expression to a variable, and then use this variable to make my template look something like this.

<ItemTemplate><br />
<%String ClassName = "myrating" + <%# DataBinder.Eval(Container.DataItem, "Day")%><br />
  <input type="radio" class="<%=ClassName %>" value="3" /><br />
  <input type="radio" class="<%="ClassName" value="4" /><br />
    </ItemTemplate><br />

This example does not compile, but I hope you get this idea.

+5
source share
4 answers

You can use the event OnItemDataBountand work with the DataItem as a variable there.

+3

MyRating.

:

   <ItemTemplate>
         <%# MyRating = "myrating" + <%# Eval(Container.DataItem, "Day")%>
         //Use the variable inside the binding(!) block 
         <%#MyRating
   </ItemTemplate>

. , .

   <ItemTemplate>
         <%# MyType = (MyType)Container.DataItem 
         <%# MyRating.Average %> 
         <%# MyRating.Count %> 
   </ItemTemplate>

, : -)

+4

, HTML- OnItemDataBound , ASP. , , , , HTML.

:

1. .

protected string className;

2. .

<asp:Literal runat="server" Visible="false" Text="<%# className = "myrating" + DataBinder.Eval(Container.DataItem, "Day") %>" />

, HTML.

3. ASP.

<ItemTemplate><br />
    <input type="radio" class="<%# className %>" value="3" /><br />
    <input type="radio" class="<%# className %>" value="4" /><br />
</ItemTemplate><br />

. .

, , ItemTemplate.

+1

/ .

(, ), script, , :

<script runat="server">
    YourNamespace.Rating current;
</script>

:

<HeaderTemplate>
    <%# (current = (YourNamespace.Rating)Eval("Day")) == null ? "" : "" %>
</HeaderTemplate>

Put it in HeaderTemplateif you want it to run only once to bind data.
== null ? "" : ""-part, is to prevent the browser from generating any generated cool html (e.g. the value of the ToStringassigned value).

0
source

All Articles