Click here to Skip to main content
14,427,367 members
Rate this:
Please Sign up or sign in to vote.
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 7:19am
Comments
Richard MacCutchan 13-Jan-20 4:38am
   
You cannot do that without converting it somehow to executable instructions.
Rate this:
Please Sign up or sign in to vote.

Solution 1

That is just JavaScript code. Use jQuery and put it in the document.ready event, $( document ).ready() | jQuery Learning Center[^]
   
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.
Rate this:
Please Sign up or sign in to vote.

Solution 2

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

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100