none
No me guarda los checkboxs seleccionados al paginar ni se obtienen estos. RRS feed

  • Pregunta

  • Hola, se muestra una lista de grupos paginada con un checkbox en cada grupo para poder seleccionarlos. Cuando se cambia de pagina no me guarda los checkboxs marcados en la pagina anterior aunque en teoría lo debería de hacer, lo mismo me pasa al querer obtener las filas de los checkboxs seleccionados cuando se pulsa el botón "AddRecomend". No se que estoy haciendo mal porque según e estado leyendo por aquí se debería hacer tal y como lo tengo. El código es el siguiente:

    <asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolder_BodyContent" runat="server">
            <form id="FindForm" method="post" runat="server">
                <p>
                    <asp:Label ID="lblNoMyGroups" meta:resourcekey="lblNoMyGroups" runat="server"></asp:Label></p>    
                <div class="field">
                    <span class="label" style="text-decoration: underline; font-weight: bold">
                        <asp:Localize ID="lclRecomend" meta:resourcekey="lblRecomend" runat="server" />
                    </span>
                    <span class="entry">
                        <asp:TextBox ID="txtRecomend" runat="server" Columns="30" />
                        <asp:RequiredFieldValidator ID="rfvRecomend" runat="server" ControlToValidate="txtRecomend"
                            Display="Dynamic" Text="<%$ Resources: Common, mandatoryField %>" CssClass="errorMessage" />
                    </span>
                </div>
                <!-- List of groups -->
                <asp:GridView ID="gvGroups" runat="server" CssClass="groups" 
                              AutoGenerateColumns="False" datakeynames="Id" 
                              onpageindexchanging="gvProducts_PageIndexChanging" 
                              onpageindexchanged="gvProducts_PageIndexChanged">
                    <Columns>
                        <asp:BoundField DataField="Name" HeaderText="<%$ Resources:common, name %>" />
                        <asp:TemplateField>
                            <ItemTemplate>                
                                <asp:CheckBox runat="server" ID="selectCheck"/>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <br />
                <!-- "Previous" and "Next" links. -->
                <div class="previousNextLinks">
                    <span class="previousLink">
                        <asp:HyperLink ID="lnkPrevious" Text="<%$ Resources:Common, Previous %>" runat="server"
                            Visible="False"></asp:HyperLink>
                    </span><span class="nextLink">
                        <asp:HyperLink ID="lnkNext" Text="<%$ Resources:Common, Next %>" runat="server" Visible="False"></asp:HyperLink>
                    </span>
                </div>
                <!-- Button of Add. -->
                <br />
                <span class="button">
                    <asp:Button ID="btnAdd" runat="server" meta:resourcekey="btnAdd" 
                OnClick="BtnAddRecomend" Width="300px" />
                </span>
            </form>
        <br />
    </asp:Content>

     public partial class AddRecomend : SpecificCulturePage
        {
            List<GroupUser> groups = new List<GroupUser>();
            List<GroupUserDTO> groupUser = new List<GroupUserDTO>();
    
            protected void Page_Load(object sender, EventArgs e)
            {
    
                    int startIndex, count;
    
                    lnkPrevious.Visible = false;
                    lnkNext.Visible = false;
                    lblNoMyGroups.Visible = false;
    
                    /* Get Start Index */
                    try
                    {
                        startIndex = Int32.Parse(Request.Params.Get("startIndex"));
                    }
                    catch (ArgumentNullException)
                    {
                        startIndex = 0;
                    }
    
                    /* Get Count */
                    try
                    {
                        count = Int32.Parse(Request.Params.Get("count"));
                    }
                    catch (ArgumentNullException)
                    {
                        count = Settings.Default.SportsEvents_defaultCount;
                    }
    
    
                    /* Get Group User */
                    UserSession userSession =
                        SessionManager.GetUserSession(Context);
    
                    /* Get the Service */
                    IUnityContainer container =
                        (IUnityContainer) HttpContext.Current.
                            Application["unityContainer"];
                    IGroupUserService groupUserService =
                        container.Resolve<IGroupUserService>();
    
                    /* Get Groups Info */
                    groupUser = groupUserService.GetMyGroups(userSession.UserProfileId,
                        startIndex, count);
    
                    if (groupUser.Count == 0)
                    {
                        lblNoMyGroups.Visible = true;
                        return;
                    }
    
                    LoadGridGroups();
    
                    /* Get the number of account operations between the required 
                     * dates, in order to manage the previous and next links
                     */
                    int numberOfGroups = groupUserService.GetNumberOfMyGroups(userSession.UserProfileId);
    
                    /* "Previous" link */
                    if ((startIndex - count) >= 0)
                    {
                        String url =
                            Settings.Default.SportsEvents_applicationURL +
                            "/Pages/AddRecomend.aspx" + "?startIndex=" + (startIndex - count) + "&count=" +
                            count;
    
                        this.lnkPrevious.NavigateUrl =
                            Response.ApplyAppPathModifier(url);
                        this.lnkPrevious.Visible = true;
                    }
    
                    /* "Next" link */
                    if ((startIndex + count) < numberOfGroups)
                    {
                        String url =
                            Settings.Default.SportsEvents_applicationURL +
                            "/Pages/AddRecomend.aspx" + "?startIndex=" + (startIndex + count) + "&count=" +
                            count;
    
                        this.lnkNext.NavigateUrl =
                            Response.ApplyAppPathModifier(url);
                        this.lnkNext.Visible = true;
                    }
            }
    
            protected void BtnAddRecomend(object sender, EventArgs e)
            {
                if (Page.IsValid)
                {
                    IUnityContainer container =
                        (IUnityContainer)HttpContext.Current.Application["unityContainer"];
                    IGroupUserService groupUserService =
                        container.Resolve<IGroupUserService>();
    
                    foreach (GridViewRow row in gvGroups.Rows)
                    {
                        CheckBox elcheckbox = (CheckBox)row.FindControl("selectCheck") as CheckBox;
                       
                        if (elcheckbox.Checked)
                        {
                            long id = (long)gvGroups.DataKeys[row.RowIndex].Value;
                            groups.Add(groupUserService.getGroupUserById(id));
                        }
                    }
                    
                    /* Get data. */
                    long eventId = Convert.ToInt64(Request.Params.Get("eventId"));
                    String description = this.txtRecomend.Text;
    
                    /* Get the Service */
                    IRecomendService recomendService =
                        container.Resolve<IRecomendService>();
    
                    /* Do action. */
                    recomendService.RecomendEvent(eventId,groups,description);
                    //String url = String.Format("./ShowEvents.aspx?keywords={0}&categoryId={1}", keywords, category);
                    //Response.Redirect(Response.ApplyAppPathModifier(url));
                    groups.Clear();
                }
            }
    
            private void LoadGridGroups()
            {
                gvGroups.DataSource = groupUser;
                gvGroups.DataBind();
            }
    
            protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                KeepSelection((GridView)sender);
    
                gvGroups.PageIndex = e.NewPageIndex;
                LoadGridGroups();
    
            }
    
            protected void gvProducts_PageIndexChanged(object sender, EventArgs e)
            {
                RestoreSelection((GridView)sender);
            }
    
            public static void KeepSelection(GridView grid)
            {
                //
                // se obtienen los id de producto checkeados de la pagina actual
                //
                List<long> checkedProd = (from item in grid.Rows.Cast<GridViewRow>()
                                         let check = (CheckBox)item.FindControl("selectCheck")
                                         where check.Checked
                                         select Convert.ToInt64(grid.DataKeys[item.RowIndex].Value)).ToList();
    
    
                //
                // se recupera de session la lista de seleccionados previamente
                //
                List<long> productsIdSel = HttpContext.Current.Session["ProdSelection"] as List<long>;
    
                if (productsIdSel == null)
                    productsIdSel = new List<long>();
    
                //
                // se cruzan todos los registros de la pagina actual del gridview con la lista de seleccionados,
                // si algun item de esa pagina fue marcado previamente no se devuelve
                //
                productsIdSel = (from item in productsIdSel
                                 join item2 in grid.Rows.Cast<GridViewRow>()
                                    on item equals Convert.ToInt64(grid.DataKeys[item2.RowIndex].Value) into g
                                 where !g.Any()
                                 select item).ToList();
    
                //
                // se agregan los seleccionados
                //
                productsIdSel.AddRange(checkedProd);
    
                HttpContext.Current.Session["ProdSelection"] = productsIdSel;
    
            }
    
            public static void RestoreSelection(GridView grid)
            {
    
                List<long> productsIdSel = HttpContext.Current.Session["ProdSelection"] as List<long>;
    
                if (productsIdSel == null)
                    return;
    
                //
                // se comparan los registros de la pagina del grid con los recuperados de la Session
                // los coincidentes se devuelven para ser seleccionados
                //
                List<GridViewRow> result = (from item in grid.Rows.Cast<GridViewRow>()
                                            join item2 in productsIdSel
                                            on Convert.ToInt64(grid.DataKeys[item.RowIndex].Value) equals item2 into g
                                            where g.Any()
                                            select item).ToList();
    
                //
                // se recorre cada item para marcarlo
                //
                result.ForEach(x => ((CheckBox)x.FindControl("chkSelection")).Checked = true);
    
            }



    miércoles, 4 de diciembre de 2013 19:57