Home | Shorter Path | About Me
Home
About Me

Archive

2004

01

02

03

04

05

06

07

08

09

10

11

12

 

2005

01

02

03

04

05

06

07

08

09

10

11

12

 

2006

01

02

03

04

05

06

07

08

09

10

11

12


Setting body tag attributes in code

Sunday, October 10, 2004 01:46 AM

Here's something that's obvious once you already know how to do it. If you don't, however, it could take a while to figure this out.

In ASP.NET, when you place controls on a web page, they have corresponding fields in the page object. These fields allow you to access and manipulate the controls in your code. Simple HTML elements, however, don't have corresponding objects - they only exist in the .aspx file. The <body> tag is one of these elements.

It turns out you can create objects that correspond to simple HTML elements, and modify these elements by setting properties in code. There are three things you have to do:

  • First, make sure the tag you want to edit has an ID, so you can call it by name. To set the ID for the <body> tag, either edit the .aspx file directly, or set the id property of the document element in the IDE (in Delphi 8, for example, open the combo box at the top of the Object Inspector, and select "DOCUMENT"). For example:

<body id=MainBody ms_positioning="FlowLayout">

  • Second, add the runat attribute to the tag and set it to "server". This is the crucial part. If you don't do that, the page object will have no knowledge of the tag and all attempts to access it as an object will result in an exception. You have to do this manually, though, by editing the .aspx file.

<body id=MainBody ms_positioning="FlowLayout" runat="server">

TWebForm1 = class(System.Web.UI.Page)
{$REGION 'Designer Managed Code'}
strict private
  procedure InitializeComponent;
{$ENDREGION}
strict private
  procedure Page_Load(sender: System.Object; e: System.EventArgs);
strict protected
  MainBody: HtmlGenericControl;
  procedure OnInit(e: EventArgs); override;
end;

Now you can use the field to manipulate the actual HTML. For example, I needed to change the page's direction based on the language selected by the user:

procedure TWebForm1.Page_Load(sender: System.Object; e: System.EventArgs);
begin
  if Request.Params['lang'] = 'hebrew' then
    MainBody.Attributes['dir'] := 'rtl'
  else
    MainBody.Attributes['dir'] := 'ltr';
end;

Copyright 2004 Yorai Aminov