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

G

Guest

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
 
N

Nathan Sokalski

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.
 
S

Steven Cheng[MSFT]

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.GetManifestResourceStream("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/subscriptions/managednewsgroups/default.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/subscriptions/support/default.aspx.

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



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

Guest

Well, let me ask a different, related question:

If I actually type client-side JS into my ASPX file in a <SCRIPT> tag, can I
access and re-write the full text content of that <SCRIPT> tag on PageLoad or
Render or something? Ideally, I'd like to write a function that steps through
all of the client-side <SCRIPT> tags 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
 
N

Nathan Sokalski

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!
 
S

Steven Cheng[MSFT]

Thanks for Nathan's input.

Hi Alex,

Theoretically speaking, you can control the content in the client <script>
....</script> block 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top