How to use page_Init in asp.net

I wrote this code below to set a theme for the selected value from the 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 the same theme to all other pages for which I wrote a function Page_Initon pages where I want to apply a theme, but this one Page_Initdoes not work on the second page. Did I miss something?

Here is the code that I write on the second page:

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

        }
+4
source share
3 answers

Try to put:

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

In the page_Load () function of this page, where you want to use the application theme, and let me know.

: PageHelper, @RononDex .

+1

cookie, , cookie .

, :

PageHelper.cs

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

Page_Init:

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

...

, cookie

,

, AutoEventWireup true. Page_init

Now, as a side note, why you are not creating a base page for this, make all the pages on your website inherit from that base page and move the theme code to the base page so that you can save the code in only one place. Or, if you use master pages, let the main page do the job.

Greetings

Leo

+1
source

All Articles