Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi everybody,
Can anyone tell me a way to alter javascript code using c#.below i have given a javascript code.In that i have to put a value in the place marked as "?".i am writing this code in html page.
XML
<script type="text/javascript">
<!--
    var image1 = new Image()
    image1.src = "test1.aspx?ImageID=?"
    var image2 = new Image()
    image2.src = "test2.aspx?ImageID=?"
    var image3 = new Image()
    image3.src = "test3.aspx?ImageID=?"
//-->
</script>

is there any way by which i can put a value in the place of ? using c#.it would be great if you could help me.thank you in advance.god bless you
Posted
Updated 15-Aug-13 4:05am
v2

One managed way to insert JS into the page while in the back-end C# code is using
RegisterClientScriptBlock, see example:
C#
ClientScriptManager cs = Page.ClientScript;
String csname1 = "PopupScript";
String csname2 = "ButtonClickScript";
StringBuilder sb = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
sb.Append("Form1.Message.value='Text from client script.'} </");
sb.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, sb.ToString(), false);


best,
H
 
Share this answer
 
v3
Comments
Joezer BH 15-Aug-13 10:09am    
5ed!
faizel s 15-Aug-13 10:45am    
can you please elaborate your solution as i am new to this javascript
Herbisaurus 18-Aug-13 1:57am    
C# code runs on the Server Side.
Javascript runs on the Clinet Side.
The whole purpose of the Server Side is to produce the HTML that will run on the Client Side, containg all sorts of things in that HTML like CSS, Javascript, Silverlight, Flash etc.

Some times, you want to manually edit and add Javascript to the page (HTML) so that is will run on the Client Side. E.G you might want to write certain JS code that depends on the parameters in the C#, instead of have that code in the JS file or blocks while it might not be needed.

RegisterClientScriptBlock is code in C# used to dynamically write a script block into the HTML page.
@faizal,

If we add a JavaScript function in .aspx file, it's code can not be changed. As suggested by Herbisaurus, you write your javascript function as a string. You have full liberty to change and write it at runtime as you want. Once you are done writing it, you have to make sure, it's read and executed as a JS function.

To do that, use RegisterClientScriptBlock and pass your string as a parameter.

Refer to http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptblock.aspx this article for more details on RegisterClientScriptBlock
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900