views:

13

answers:

1

hi all

Is it possible filtering a list in a content page by a value set in its master page? I mean when a user clicks on a link button in master page a variable is set and then based on the value that variable, when loading a content page, a list in it is filtered?

+2  A: 

Yes, definitely. The only trick is to cast Page.Master to the type of master page that you're using.

Here's a quick example I whipped up:

MasterPage.master

<asp:Button runat="server" ID="btnToggleEvensOnly" Text="Toggle Even Number Filtering" OnClick="btnToggleEvensOnly_Click" />
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>

MasterPage.master.cs

public bool IsFiltered
{
    get
    {
        return ViewState["isFiltered"] == null ? false : (bool) ViewState["isFiltered"];
    }
    set
    {
        ViewState["isFiltered"] = value;
    }
}

protected void btnToggleEvensOnly_Click(object sender, EventArgs e)
{
    IsFiltered = !IsFiltered;
}

Default.aspx

<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server" >
<asp:Repeater runat="server" ID="rptList">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr><td><%# Eval("i") %></td></tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
</asp:Content>

Default.aspx.cs

protected override void OnPreRender(EventArgs e)
{
    List<MyItem> items = new List<MyItem>();
    for (int i = 0; i < 10; i++)
    {
        items.Add(new MyItem { i = i });
    }

    var query = items.AsEnumerable();
    if (((MasterPage)Master).IsFiltered)
    {
        query = query.Where(mi => mi.i % 2 == 0);
    }

    rptList.DataSource = query;
    rptList.DataBind();

    base.OnPreRender(e);
}

public class MyItem
{
    public int i { get; set; }
}
roufamatic