473,387 Members | 3,750 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Refering to <asp:...> Controls in Client-Side JavaScript

I frequently find myself wanting to insert some basic client-side JavaScript
functions in the page of an ASPX of mine. But I find it so frustrating that I
have to actually contruct my JavaScript in C# on the server-side and render
it to the client because I can't use the IDs of my controls as they are
written in the HTML page itself. Rather, I have to use Control.ClientID to
get that ID that I can use in the client-side JS.

So my question is, is there a more elegant way of doing this? If not, is
there some way that I could write something that would scan the static JS
that I've put on any page before rendering that page and replace control
references with Control.ClientID or something like that?

Alex
Jul 28 '06 #1
5 2194
If you wanted to, you could create a method that reads the scripts from a
text file and replaces the appropriate parts with what you want. Or, as a
way of reducing the amount of JavaScript you add dynamically you could write
static JavaScript functions that accept objects as parameters, and then
simply dynamically create the call that passes those parameters. Those are
the only suggestions I know of that would solve your problem.
--
Nathan Sokalski
nj********@hotmail.com
http://www.nathansokalski.com/

"Alex Maghen" <Al********@newsgroup.nospamwrote in message
news:25**********************************@microsof t.com...
>I frequently find myself wanting to insert some basic client-side
JavaScript
functions in the page of an ASPX of mine. But I find it so frustrating
that I
have to actually contruct my JavaScript in C# on the server-side and
render
it to the client because I can't use the IDs of my controls as they are
written in the HTML page itself. Rather, I have to use Control.ClientID to
get that ID that I can use in the client-side JS.

So my question is, is there a more elegant way of doing this? If not, is
there some way that I could write something that would scan the static JS
that I've put on any page before rendering that page and replace control
references with Control.ClientID or something like that?

Alex

Jul 29 '06 #2
Thanks for Nathan's good suggestions.

Hi Alex,

I think Nathan's suggestion on creating some script template files and load
script fragment from them at runtime is a good idea. Also, more
specifically, you can consider the following means:

1). create a separate class library project

2) create some script template files(text files) which contains the scritp
functions/template functions and compiled them as "embeded resources" in
that class library project.

3). Reference that class library in your ASP.NET web application so that
you can dynamically load the script/template files as resource stream from
the class library assembly. e.g.

===============
protected void Page_Load(object sender, EventArgs e)
{
Stream stream =
typeof(WSProxyLib.Class1).Assembly.GetManifestReso urceStream("WSProxyLib.scr
ipttemplate.txt");

StreamReader sr = new StreamReader(stream);

string template = sr.ReadToEnd();

Response.Write("<br/>" + Server.HtmlEncode(template));
}
===============
Also, you can use the "WebResource" feature to link external files(css or
script files that embeded in .net assembly) in your asp.net page

#WebResource ASP.NET 2.0 explained
http://www.codeproject.com/aspnet/MyWebResourceProj.asp
In addition, if you do want to put the script functions in aspx template
and utilize the server control's "ClientID" property, you can consider
using the <%= % expression to embed ClientID into script. e.g.

================
<head runat="server">
<title>Untitled Page</title>

<script language="javascript" >
function testfunc()
{
var id = "<%= Button1.ClientID %>";
var elm = document.getElementById( id );

alert(elm.value);
}
</script>
</head>
================

You can tried this in your aspx page if there is just some simple script
snippets. However, we still recommend that you consider using a template
file and load it at runtime because embed <%= %will make the code logic
mixed with UI template in aspx which is not good practice generaly.
Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

==================================================

Get notification to my posts through email? Please refer to

http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial

response from the community or a Microsoft Support Engineer within 1
business day is

acceptable. Please note that each follow up response may take approximately
2 business days

as the support professional working with you may need further investigation
to reach the

most efficient resolution. The offering is not appropriate for situations
that require

urgent, real-time or phone-based interactions or complex project analysis
and dump analysis

issues. Issues of this nature are best handled working with a dedicated
Microsoft Support

Engineer by contacting Microsoft Customer Support Services (CSS) at

http://msdn.microsoft.com/subscripti...t/default.aspx.

==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.


Jul 31 '06 #3
Well, let me ask a different, related question:

If I actually type client-side JS into my ASPX file in a <SCRIPTtag, can I
access and re-write the full text content of that <SCRIPTtag on PageLoad or
Render or something? Ideally, I'd like to write a function that steps through
all of the client-side <SCRIPTtags already embedded in the ASPX page and
cleans them up before the page is delivered.

Can the Page.ClientScript object give me access to a collection of already
existent client-side scripts on the page? If not, is there another way that I
could iterate through any client-scripts already on the page and edit them
pre-delivery?

Alex


"Steven Cheng[MSFT]" wrote:
Thanks for Nathan's good suggestions.

Hi Alex,

I think Nathan's suggestion on creating some script template files and load
script fragment from them at runtime is a good idea. Also, more
specifically, you can consider the following means:

1). create a separate class library project

2) create some script template files(text files) which contains the scritp
functions/template functions and compiled them as "embeded resources" in
that class library project.

3). Reference that class library in your ASP.NET web application so that
you can dynamically load the script/template files as resource stream from
the class library assembly. e.g.

===============
protected void Page_Load(object sender, EventArgs e)
{
Stream stream =
typeof(WSProxyLib.Class1).Assembly.GetManifestReso urceStream("WSProxyLib.scr
ipttemplate.txt");

StreamReader sr = new StreamReader(stream);

string template = sr.ReadToEnd();

Response.Write("<br/>" + Server.HtmlEncode(template));
}
===============
Also, you can use the "WebResource" feature to link external files(css or
script files that embeded in .net assembly) in your asp.net page

#WebResource ASP.NET 2.0 explained
http://www.codeproject.com/aspnet/MyWebResourceProj.asp
In addition, if you do want to put the script functions in aspx template
and utilize the server control's "ClientID" property, you can consider
using the <%= % expression to embed ClientID into script. e.g.

================
<head runat="server">
<title>Untitled Page</title>

<script language="javascript" >
function testfunc()
{
var id = "<%= Button1.ClientID %>";
var elm = document.getElementById( id );

alert(elm.value);
}
</script>
</head>
================

You can tried this in your aspx page if there is just some simple script
snippets. However, we still recommend that you consider using a template
file and load it at runtime because embed <%= %will make the code logic
mixed with UI template in aspx which is not good practice generaly.
Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

==================================================

Get notification to my posts through email? Please refer to

http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial

response from the community or a Microsoft Support Engineer within 1
business day is

acceptable. Please note that each follow up response may take approximately
2 business days

as the support professional working with you may need further investigation
to reach the

most efficient resolution. The offering is not appropriate for situations
that require

urgent, real-time or phone-based interactions or complex project analysis
and dump analysis

issues. Issues of this nature are best handled working with a dedicated
Microsoft Support

Engineer by contacting Microsoft Customer Support Services (CSS) at

http://msdn.microsoft.com/subscripti...t/default.aspx.

==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.


Jul 31 '06 #4
You can't stop the ones in the *.aspx file from getting delivered, but if
you really wanted to you could read the *.aspx file as a text file,
manipulate the text that is in the file, and then add the result to what is
sent to the browser. However, I would not suggest this, because it would
involve extra manipulation code to parse out the stuff in the *.aspx file
that is not part of the script, and the original script would still get sent
as well. If you want to read and manipulate a script from another file, I
would create an extra text file with the code you want to manipulate so that
you only send the script that you want. However, I think you are putting
yourself through a lot of extra work using extra text files and
manipulation, it is much easier to simply generate the script and send it
with Page.ClientScript.RegisterClientScriptBlock(). Good Luck!
--
Nathan Sokalski
nj********@hotmail.com
http://www.nathansokalski.com/

"Alex Maghen" <Al********@newsgroup.nospamwrote in message
news:DB**********************************@microsof t.com...
Well, let me ask a different, related question:

If I actually type client-side JS into my ASPX file in a <SCRIPTtag, can
I
access and re-write the full text content of that <SCRIPTtag on PageLoad
or
Render or something? Ideally, I'd like to write a function that steps
through
all of the client-side <SCRIPTtags already embedded in the ASPX page and
cleans them up before the page is delivered.

Can the Page.ClientScript object give me access to a collection of already
existent client-side scripts on the page? If not, is there another way
that I
could iterate through any client-scripts already on the page and edit them
pre-delivery?

Alex


"Steven Cheng[MSFT]" wrote:
>Thanks for Nathan's good suggestions.

Hi Alex,

I think Nathan's suggestion on creating some script template files and
load
script fragment from them at runtime is a good idea. Also, more
specifically, you can consider the following means:

1). create a separate class library project

2) create some script template files(text files) which contains the
scritp
functions/template functions and compiled them as "embeded resources" in
that class library project.

3). Reference that class library in your ASP.NET web application so that
you can dynamically load the script/template files as resource stream
from
the class library assembly. e.g.

===============
protected void Page_Load(object sender, EventArgs e)
{
Stream stream =
typeof(WSProxyLib.Class1).Assembly.GetManifestRes ourceStream("WSProxyLib.scr
ipttemplate.txt");

StreamReader sr = new StreamReader(stream);

string template = sr.ReadToEnd();

Response.Write("<br/>" + Server.HtmlEncode(template));
}
===============
Also, you can use the "WebResource" feature to link external files(css or
script files that embeded in .net assembly) in your asp.net page

#WebResource ASP.NET 2.0 explained
http://www.codeproject.com/aspnet/MyWebResourceProj.asp
In addition, if you do want to put the script functions in aspx template
and utilize the server control's "ClientID" property, you can consider
using the <%= % expression to embed ClientID into script. e.g.

================
<head runat="server">
<title>Untitled Page</title>

<script language="javascript" >
function testfunc()
{
var id = "<%= Button1.ClientID %>";
var elm = document.getElementById( id );

alert(elm.value);
}
</script>
</head>
================

You can tried this in your aspx page if there is just some simple script
snippets. However, we still recommend that you consider using a template
file and load it at runtime because embed <%= %will make the code logic
mixed with UI template in aspx which is not good practice generaly.
Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

================================================= =

Get notification to my posts through email? Please refer to

http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent
issues
where an initial

response from the community or a Microsoft Support Engineer within 1
business day is

acceptable. Please note that each follow up response may take
approximately
2 business days

as the support professional working with you may need further
investigation
to reach the

most efficient resolution. The offering is not appropriate for situations
that require

urgent, real-time or phone-based interactions or complex project analysis
and dump analysis

issues. Issues of this nature are best handled working with a dedicated
Microsoft Support

Engineer by contacting Microsoft Customer Support Services (CSS) at

http://msdn.microsoft.com/subscripti...t/default.aspx.

================================================= =

This posting is provided "AS IS" with no warranties, and confers no
rights.



Jul 31 '06 #5
Thanks for Nathan's input.

Hi Alex,

Theoretically speaking, you can control the content in the client <script>
....</scriptblock in the aspx template by the following means:

1. still use the <%= PageVariable %render expression to inject text
content into aspx output. e.g.

=====in aspx==========
<head runat="server">
.....................
<script id="script2" language="javascript" type="text/javascript">
<%= InlineScript %>
</script>
.....................
</head>
.................................

========in page code=========
public partial class ASPNETPage : System.Web.UI.Page
{
protected string InlineScript;

protected void Page_Load(object sender, EventArgs e)
{
InlineScript =
@"function TestFun2()
{
alert('test function2!');
}
";

}
}
=============================

2. put an ASP.NET Literal control in the <script block and assign the
script functions to the Literal control's "Text" property in code behind.
e.g

======in aspx=========
<head runat="server">
.....................................
<script id="script1" language="javascript" type="text/javascript">

<asp:Literal id="ltScript" runat="server" ></asp:Literal>

</script>
..................
</head>

==========in code behind=============
public partial class ASPNETPage : System.Web.UI.Page
{

protected string InlineScript;
protected void Page_Load(object sender, EventArgs e)
{
ltScript.Text =

@"function TestFun()
{
alert('test function!');
}
";

}
}
=========================

However, the above means is not recommended, we would prefer using the
Page.ClientScript.XXX method for registering startup script or script
block. These functions will ensure the scritp block be inserted in the
proper location in the page output.

Hope this helps further.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.


Aug 1 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Chris Fink | last post by:
Hello, Does anyone know of a way to handle broken href image tags either by using the html img tag or the asp:image server control? For example, if my src attribute is broken, I would like to...
5
by: Ken Dopierala Jr. | last post by:
Hi, This is just a query about what people use most. Up until today I've been using <asp:Table> tags to build my tables. We just outsourced our HTML design to a local guy and when I got it back...
4
by: z. f. | last post by:
Hi, I'm having an aspx page with a server form. i have a grid with a delete button and below the grid, another area with inputs for inserting new values and an "add" button for submiting the...
5
by: George Durzi | last post by:
I currently have an href inside of an asp:repeater <a href='<%# String.Concat("PDFReader.aspx?id=", DataBinder.Eval(Container.DataItem, "ProductUniqueId")) %>' target="_blank">View</a> ...
4
by: Alan Silver | last post by:
Hello, I would like to know if it is possible to use a panel, but prevent it from adding a <div> tag to the HTML. The reason I want to do this is that I am using a panel to enable me to...
0
by: CharlesA | last post by:
Hi folks, I'm using ASP.net 1.1 with C# I've got this kind of thing going <div class="row"> <label class="col1">Rm Name</label> <asp:textbox id="txtRM" runat="server" cssclass="col2"...
5
by: Nathan Sokalski | last post by:
My Web.config file contains the following section to register some of my UserControls: <pages> <controls> <add tagPrefix="NATE" tagName="Banner" src="~/Banner.ascx"/> <add tagPrefix="NATE"...
4
by: Anastasios Hatzis | last post by:
I'm looking for a pattern where different client implementations can use the same commands of some fictive tool ("foo") by accessing some kind of API. Actually I have the need for such pattern for...
3
by: ajay2552 | last post by:
Hi, I have a query. All html tags start with < and end with >. Suppose i want to display either '<' or '>' or say some text like '<Company>' in html how do i do it? One method is to use &lt,...
0
by: reema | last post by:
EJB Interview Questions http://interviewdoor.com/technical/EJB-Interview-Questions.htm CSS Interview Questions http://interviewdoor.com/technical/CSS-Interview-Questions.htm C Interview Questions...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.