Adding Server Side code in a Client Side Script???

G

Guest

Hi,
I am trying to add some server side code in some Client Side Script. I can
get it to work properly with the code embedded directly in the .aspx page.
However, if I try to use the Page.ClientScript.RegisterClientScriptBlock I
get an error and the code does not execute.

Here is an example:

protected void Page_Load(object sender, EventArgs e)
{
FileStream strm = File.OpenRead("<<Path to Script goes here>>");
StreamReader rdr = new StreamReader(strm);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OCL",
rdr.ReadToEnd());
}

-- Script in File. --
<script language="javascript" type="text/javascript">
function GetClientIPAddress()
{
alert("<%
Response.Write(Request.ServerVariables["REMOTE_ADDR"].ToString()); %>");
}
<script/>

Any ideas?
Thanks,
- Mike
 
G

Guest

Mike,
if you view source on your generated page, you wll see that "what you did is
what you get":

<script language="javascript" type="text/javascript">
function GetClientIPAddress()
{
alert("<%
Response.Write(Request.ServerVariables["REMOTE_ADDR"].ToString()); %>");
}
<script/>

The Solution is to get the REMOTE_ADDR string in your server side code, and
add this as a string literal rather than in server-side script delimiters to
the client script you add to the page, e.g.:

string remoteIp=Request.ServerVariables["REMOTE_ADDR"].ToString());

then,

string scr=@"<script language=\"javascript\" type=\"text/javascript\">
function GetClientIPAddress()
{
alert(" +remoteIp +");
}
<script/>";

then RegisterClientScriptBlock with string "str"




HTH,
Peter
 

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

Forum statistics

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

Latest Threads

Top