Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wan to execute code on page load event from string. Server Side C#

Example

string code = "divmainmenu.Style["display"] = "block";"

    protected void Page_Load(object sender, EventArgs e)
                {
                    if(!IsPostBack)
                    { 
                       // Execute my string here like.

                          Execute(code);
                     }
                }


What I have tried:

i cant found about this type of solutions.
Posted
Updated 15-Jan-20 6:19am
Comments
Richard MacCutchan 13-Jan-20 4:38am    
You cannot do that without converting it somehow to executable instructions.

That is just JavaScript code. Use jQuery and put it in the document.ready event, $( document ).ready() | jQuery Learning Center[^]
 
Share this answer
 
Comments
Member 14041670 18-Jan-20 4:52am    
Yes you are right thanks for your valuable reply. java script instead of c# code but there is some other issue when i call java scrip code behind c# in content page its not working. can you help with below code.
its working without content page, but i need it with content page. thank you.



//C# code

foreach (string showmenu in listmainmenu)
{


//java script in string

string str = " document.getElementById('<%= Page.Master.FindControl(\"forms\").FindControl(\"" + showmenu.ToString() + "\").ClientID %>').style.display = \"Block\";";

//call javascript
Page.ClientScript.RegisterStartupScript(this.GetType(), "myscript"+showmenu, str, false);

}
ZurdoDev 18-Jan-20 14:20pm    
I would suggest not using C# to try and call JavaScript. It's a bad approach in my opinion. Instead, do it all in JavaScript.

Otherwise, do not use Page.Master.FindControl because that doesn't always work. Instead view the source of your page and find the actual ids and then hard code them in.
Your C# code will treat your HTML as a plain string. If you want to access an element from your form in code behind then you have to set runat="server" attribute for that element and assign a unique ID to it so the server can access it. For example:

ASPX:
ASP.NET
<div id="divmainmenu" runat="server" />


Then in your C# code, you can reference the element by its ID and set the style Controls.Attributes.Add method:
C#
protected void Page_Load(object sender, EventArgs e)
{
	if(!IsPostback){
        	divmainmenu.Attributes.Add("style", "display:block;");// Where Style is the Attribute
	}
}


Otherwise, you can handle that at the client-side using JavaScript or jQuery as already suggested.
 
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