Solved

Specifying properties for HTML controls, user(ascx) controls at runtime

Posted on 2004-10-06
16
298 Views
Last Modified: 2006-11-17
Hello,

I'm new to ASP.NET and I 've run across the problem of setting the attributes of some HTML controls at runtime. For example, I have the HTML statements
<link rel='stylesheet' type='text/css' href=''>
and
<script language='javascript' src=''>
Now I want to specify the href and src attribute values at runtime but I don't know how to do that with .NET. With classic ASP, I used to do href='<%= stylesheetName %>' but with .NET I am unable to find equivalent server control for the link and script tags. Please help.

Also if included a user control (.ascx file) in my .aspx page as
<myNamespace:myControl id="HeaderControl" PageTitle="Hello">,
is it possible to specify the value of the PageTitle attribute in the code-behind file (at runtime) rather than specifying it at design-time as I have done above.

Thanks a lot.
0
Comment
Question by:bmgun
  • 6
  • 5
  • 5
16 Comments
 
LVL 9

Expert Comment

by:hismightiness
ID: 12245092
You can do both in similar ways.  The first would probably be easier to just use a string:

HTML:
<script language='javascript' src='<%= strMySource %>'>

CODE BEHIND:
Dim strMySource as String

' in an event somewhere, probably Page_Load
strMySource = "mystringvalue.js"


The control title could be done the same way, but you will need to try it to fine out:

HTML:
<myNamespace:myControl id="HeaderControl" PageTitle='<%= strMyTitle %>'>

CODE BEHIND:
Dim strMyTitle as String

' in an event somewhere, probably Page_Load
strMyTitle = "Page Title"
0
 
LVL 9

Expert Comment

by:hismightiness
ID: 12245097
Another way is to use a literal control.  It is much the same way, just using a Server Control.  However, it will not work with your Control page title example.
0
 
LVL 15

Assisted Solution

by:Thogek
Thogek earned 300 total points
ID: 12245848
hismightiness's initial suggestion above is probably the simplest way to do what you're looking for, and probably the way I'd do it myself.

Another (perhaps more .NET Purist) way is to add the runat="server" to your tags, something like:

    <script language="javascript" runat="server" id="scr1">

and then, in your code-behind class, declare

    HtmlGenericControl scr1;

and add within your code (such as in Page_Load):

    scr1.Attributes.Add("src", "MyJSFilePath.js");

I'm assuming C# syntax, here.

Mroe about the HtmlGenericControl at http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemwebuihtmlcontrolshtmlgenericcontrolclasstopic.asp
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:bmgun
ID: 12252814
Thanks to both of you guys for your replies. I tried out both the answers and they both work for the simple html tags (For the first option, I needed to use Public strMySource instead of Dim strMySource because Dim defaults to Private) but am getting errors when I tried the same thing with user controls.

On trying the first option(hismightiness) with user controls, it does not recognize the <%= %> tags when they are in quotes and they are printed out as it is in the rendered html (when I did view source). If I remove the quotes, I get the error message
"Parser Error: Server tags cannot contain <% ... %> constructs."
On trying the second option with user controls (Thogek -- see code below), even though I added an attribute using logo1.Attributes.Add( ) the rendered html was simply blank as if I hadn't added any attribute. ie. it was rendered as <img src='' .....   instead of <img src='/images/logo.gif' .....

USER CONTROL (myLogo.ascx)

HTML
<img src='<%= UrlLogoGif %>' width='100' height='25' alt='' border='0'><br>

CODEBEHIND
Public Class myLogo
    Inherits System.Web.UI.UserControl
    Public UrlLogoGif As String

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub
End Class

INDEX PAGE (index.aspx)

HTML
<%@ Register TagPrefix="Tools" TagName="myLogo" Src="myLogo.ascx" %>
....
                                        <Tools:myLogo id="logo1" runat="server" />

CODEBEHIND
        Public logo1 As UserControl
....
        logo1.Attributes.Add("UrlLogoGif", "/images/logo.gif")

0
 
LVL 9

Expert Comment

by:hismightiness
ID: 12252954
You need to assign the value before the UserControl is rendered.  Try putting your string assignment in an earlier event like Page_PreRender, or Page_Init.
0
 

Author Comment

by:bmgun
ID: 12254475
hismightiness, could you explain which string assignment that I should put in the Page_Init event ? I was trying to place different things in the Page_Init event but nothing seems to work. I get the same errors as before. Thanks.
0
 
LVL 15

Expert Comment

by:Thogek
ID: 12255665
If the image in question exists within your User Control (myLogo.ascx), then your User Control's code-behind would need to have something like:

    Public logo1 As UserControl

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        logo1.Attributes.Add("UrlLogoGif", "/images/logo.gif")
    End Sub
0
 
LVL 15

Expert Comment

by:Thogek
ID: 12255678
Oops.  Ignore that.  I mixed up your two cases.  (Doh.)

Try, for your image-containing user-control (myLogo.ascx):

HTML
    <img src='<%= UrlLogoGif %>' width='100' height='25' alt='' border='0'><br>

CODEBEHIND
    Public Class myLogo
        Inherits System.Web.UI.UserControl
        Public UrlLogoGif As String
   
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Put user code to initialize the page here
            UrlLogoGif = "/images/logo.gif"  ' this needs to happen before the Render phase
        End Sub
    End Class
0
 
LVL 15

Expert Comment

by:Thogek
ID: 12255682
Note that if Tools:myLogo is your own custom user control, then simply adding to its Attributes collection won't do any good until your user control's code-behind class does something with its Attributes.

Perhaps, since UrlLogoGif is a public field of myLogo, instead of
    logo1.Attributes.Add("UrlLogoGif", "/images/logo.gif")
you could try
    logo1.UrlLogoGif = "/images/logo.gif"
and just place that inside your page's Page_Init or Page_Load.

This would seem to replace the assignation of UrlLogoGif in my previous post.  (Boy am I confusing myself tonight.)
0
 
LVL 9

Assisted Solution

by:hismightiness
hismightiness earned 100 total points
ID: 12258017
USER CONTROL (myLogo.ascx)

HTML
<img src='<%= UrlLogoGif %>' width='100' height='25' alt='' border='0'><br>

CODEBEHIND
Public Class myLogo
    Inherits System.Web.UI.UserControl
    Dim _urlLogoGif as String
    Public Property UrlLogoGif() As String
        Get
            return _urlLogoGif
        End Get
        Set(ByVal Value As String)
            _urlLogoGif = Value
        End Set
    End Property

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub
End Class

INDEX PAGE (index.aspx)

HTML
<%@ Register TagPrefix="Tools" TagName="myLogo" Src="myLogo.ascx" %>
....
                                        <Tools:myLogo id="logo1" runat="server" />

CODEBEHIND
        Public logo1 As UserControl
....
        logo1.UrlLogoGif = "/images/logo.gif"
0
 

Author Comment

by:bmgun
ID: 12262239
I am not even able to compile the assignment
   logo1.UrlLogoGif = "/images/logo.gif"

UrlLogoGif is not recognized as a valid property of the generic WebControl class.

index.aspx.vb(30): 'UrlLogoGif' is not a member of 'System.Web.UI.UserControl'.

And with regards to placing the above assignment in the code-behind of the User Control itself, that is same as specifying it statically in the HTML of index.aspx.
0
 
LVL 9

Expert Comment

by:hismightiness
ID: 12262989
Hmm...  Try this then.  That should've worked.

    Public Shared Property UrlLogoGif() As String
        Get
            return _urlLogoGif
        End Get
        Set(ByVal Value As String)
            _urlLogoGif = Value
        End Set
    End Property
0
 

Author Comment

by:bmgun
ID: 12263434
Hi hismightiness,

I tried making the property Shared but I got this compiler error.

"Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class."

Why do you say that the previous one should've worked ? If we declared logo1 as UserControl, then won't the members of UserControl and its base classes be the only ones that are available to logo1 ? Thanks.
0
 
LVL 15

Accepted Solution

by:
Thogek earned 300 total points
ID: 12264236
Change

    Public logo1 As UserControl

to

    Public logo1 As myLogo

or, if your myLogo class is using a namespace

    Public logo1 Ad yourNameSpace.myLogo
0
 

Author Comment

by:bmgun
ID: 12264415
Great !!! That worked. Thanks to both of you for all your help to get me out of this struggle.
0
 
LVL 9

Expert Comment

by:hismightiness
ID: 12264572
D'oh!  I hate it when I miss things like that.  Good call, Thogek!  Thank you bmgun.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question