Solved

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

Posted on 2004-10-06
16
291 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:bmgun
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 15

Expert Comment

by:Thogek
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
D'oh!  I hate it when I miss things like that.  Good call, Thogek!  Thank you bmgun.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now