user2835256
user2835256

Reputation: 415

How to use Page_Init in asp.net

I wrote this code below to set theme to selected value from list, it works for this page:

  protected void Page_Init(object sender, EventArgs e)
    {
        HttpCookie c = Request.Cookies["theme"];
        Page.Theme = c == null ? "Aqua" : c.Value;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie c = Request.Cookies["theme"];
        if (!IsPostBack && (c != null))
            rbList.Value = c.Value;
    }

Problem: I want to apply same theme to all other pages for which i wrote Page_Init function in the pages where i want to apply theme, but this Page_Init doesn't work in second page. am i missing any thing??

Here is the code i am writing in second page:

 protected void Page_Init(object sender, EventArgs e)
        {
            HttpCookie c = Request.Cookies["theme"];
            Page.Theme = c == null ? "Aqua" : c.Value;

        }

Upvotes: 4

Views: 40246

Answers (3)

Leo
Leo

Reputation: 14860

Things to try...

Make sure the cookie is sent in the request

Make sure the theme is not getting overridden later in the page life cycle

Make sure the page has AutoEventWireup set to true in the page markup. Otherwise your Page_init will be treated as a simple method

Now, as a side note why dont you create a base page for this, make all pages in your website inherit from this base page and move the theme code to the base page so you can keep the code in just one place. Or if you are using master pages let the master page do this job.

Cheers

Leo

Upvotes: 1

Tameen Malik
Tameen Malik

Reputation: 1268

Please try to put:

 HttpCookie c = Request.Cookies["theme"];

In Page_Load() Function of that page where you want to use the applied theme, & let me know it's result.

Suggestion: Use PageHelper as @RononDex suggested you to use above.

Upvotes: 1

RononDex
RononDex

Reputation: 4183

Check the lifespan of your cookies, maybe the cookie gets removed just shortly after you set it.

I would highly advice you to at least put that logic in a static function, that way you don't have redundant code on all pages:

PageHelper.cs

public static class PageHelper
{
    public static void SetThemeFromCookie(Page page)
    {
        HttpCookie c = Request.Cookies["theme"];
        page.Theme = c == null ? "Aqua" : c.Value;
    }
}

And in your Page_Init methods:

 protected void Page_Init(object sender, EventArgs e)
 {
     PageHelper.SetThemeFromCookie(this);
 }

Upvotes: 2

Related Questions