Wednesday, January 28, 2009

Problem overriding Page.InitializeCulture in ASP.NET

Some articles on MSDN said that you can do some magic things using culture. You can see it in http://msdn.microsoft.com/en-us/library/bz9tc508.aspx. It is good when inherited page that does not use master page and the ASP.NET page is directly derived from Page class.

It will be a problem if you are not directly inherit from a page class expecially if you define a contentplaceholder in your masterpage, and use it in your inherited page.

Quick example:

File : Masterpage.master

<%@ Master Language="C#" AutoEventWireup="true" Codebehind="MasterPage.Master.cs"
Inherits="Yourpage.Master" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Your Master Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ContentPlaceHolder ID="cph1" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>


File: Inherited.cs




Public Class Inherited : System.Web.UI.Page


{


      Protected override void  InitializeCulture()


     {


            base.InitializeCulture();


            // do it your own


     }


}



File: YourASP.aspx




<%@ Page Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"    Codebehind="YourASP.aspx.cs" Inherits=""YourASP" Title="Untitled Page" %>


<asp:Content ID="Content1" ContentPlaceHolderID="cp1" runat="server">
</asp:Content>



File: YourASP.aspx.cs




public partial class YourASP : Inherited 





          /// Make it your own methods or whatever




}



The problem is when I add any ASP.NET controls into Content1, The control will not be displayed. I already make some debug and find out in watch that Template_cp1 is null. You can see it in debug visualization. Just browse its visualization to instance of the Master property of that page, drill down to ASP.Masterpage_master, you can see that Template is set to null.



That is solved when I am not overriding InitializeCulture. In Template property, it will set to System.Web.UI.CompiledTemplateBuilder instance, so any controls you define in Content1 will be displayed.



To provide your own culture mechanism, do not override InitializeCulture methods. You can use any override methods like OnPreInit or OnInit or others to initialize your own culture mechanism.



Technorati Tags: ,,

0 comments: