How do I do conditional logic within an ASP.NET DataRepeater control?

旧街凉风 提交于 2019-12-10 19:36:57

问题


I'm binding my DataRepeater control to a table that has many columns. I'd like to only display a subset of those, depending on what is populated.

How/where should I do my contitional tests within a dataRepeater? This is the code within my itemtemplate:

<% if (0= (DataBinder.Eval(Container.DataItem, "first").ToString().Length))
{
   i++;
}
    %>

The error I get is: CS0103: The name 'Container' does not exist in the current context


回答1:


You should be fine with this:

<% if (0 == (Eval("first").ToString().Length))
{
   i++;
}
%>

But depending on what you want to do, I would probably write a function to handle the binding of the data in order to retain separation between display and business logic.

e.g.

in your aspx:

<asp:Repeater id="myRepeater" runat="server" onDataItemBound="FillInRepeater">
<ItemTemplate>
<div class="contactLarge">
    <div style="background-color:#C5CED8;clear:both"><asp:Label runat="server" ID="title"></asp:Label>
    .
    .
    .
</div>
</ItemTemplate>
<AlternatingItemTemplate>
</AlternatingItemTemplate>
</asp:Repeater>

in your code-behind:

protected void FillInRepeater(object sender, RepeaterItemEventArgs e)
{
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
    //in here you bind to your repeater labels and stuff then do all that sorta logic.
    //Grab Primary Data
    string titleText = DataBinder.Eval(e.Item.DataItem, "title").ToString();
    string somethingElseText = DataBinder.Eval(e.Item.DataItem, "somethingElse").ToString();
    string maybeSeeMaybeDontText = DataBinder.Eval(e.Item.DataItem, "maybeSeeMaybeDont").ToString();

    //Find the controls and populate them according the to row
    Label titleLabel = (Label)e.Item.FindControl("title");
    Label somethingElseLabel = (Label)e.Item.FindControl("somethingElse");
    Label maybeSeeMaybeDontLabel = (Label)e.Item.FindControl("maybeSeeMaybeDont");

    // display the fields you want to
    titleLabel.Text = titleText;
    somethingElseLabel.Text = somethingElseText;

    // here is where you could do some of your conditional logic
    if (titleText.Length != 0 && somethingElseText.Length != 0)
    {
        maybeSeeMaybeDontLabel.Text = maybeSeeMaybeDontText;
    }
  }
}

personally, I prefer to do things this way rather than doing any logic inside the ASP. I know that it might seem a bit silly to some people, but I like to keep my business logic separate from my display logic whereever possible.



来源:https://stackoverflow.com/questions/3464470/how-do-i-do-conditional-logic-within-an-asp-net-datarepeater-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!