Redirect if only one item in repeater

Delford Chaffin asked on April 17, 2014 17:17

I have a custom search results page and if only one result is returned, I want to redirect users to the found item. I have a SQL Data Source that brings in Documents from a Stored Procedure and binds them to a repeater.

I was trying to customize the layout of the repeater and add a Page_Load or PreRender event that would check the number of items in the repeater, but this is not working for me.

Does anyone know the most efficient way to grab the number of items in that Repeater (or the data source)?

Thanks!

Recent Answers


Brenden Kehren answered on April 17, 2014 20:19

In your transformation you can use <%# DataRowView.DataView.Count == 1 %>. If the repeater contains exactly 1 item you might be able to redirect them like this <%# (DataRowView.DataView.Count == 1 ? Response.Redirect(GetDocumentUrl()) : "") %> Haven't tested this so you may have to use some javascript if this doesn't redirect you. I know the DataView.Count will get you the item count though.

0 votesVote for this answer Mark as a Correct answer

Delford Chaffin answered on April 18, 2014 09:35

Thanks, that worked in terms of printing the row count, but when it went to redirect (per your example), I got: "Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'string'".

What I ended up doing was in the Repeater Layout:

<%@ Control Language="C#" AutoEventWireup="true" Inherits="CMSWebParts_Viewers_Basic_BasicRepeater" CodeFile="~/CMSWebParts/Viewers/Basic/BasicRepeater.ascx.cs" %>

<script runat="server">

  protected override void OnPreRender(EventArgs e)
  {
    base.OnPreRender(e);
    if(this.DataSourceControl != null)
    {
      System.Data.DataSet ds = (System.Data.DataSet)this.DataSourceControl.DataSource;
      if(!DataHelper.DataSourceIsEmpty(ds))
      {
        int rowCount = ds.Tables[0].Rows.Count;
        if(rowCount == 1)
        {
          Response.Redirect("~/"+ds.Tables[0].Rows[0]["URLSlug"]);
        }
      }
    }
  }

</script>

<asp:PlaceHolder runat="server" ID="plcBasicRepeater" />
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.