User
User

Reputation: 3274

Executing C# code on first page load

I have a public static method string SomeMethod(string message) inside a SomeClass class which gets a string as input and returns something like

<div>message</div>

Of course this is over-simplificated, but the idea is just like this. Now I would like to do something like

<script language="javascript">var string = <% $SomeClass.SomeMethod('asdada');></script>

the first time the page is loaded, but I don't really know how can I do it. That just gives me an "object expected" error in JavaScript. Can anyone please help me out with this?

Upvotes: 1

Views: 383

Answers (3)

GvS
GvS

Reputation: 52518

If you want your server side tags to output something, you should use:

 <%: yourCode %>

Your code, invokes the method, but does not send the output to the page:

 <script>var string=<% yourMethodCall() %></script>
 /* Result = */
 <script>var string=</script>
 /* ASP.Net code is translated to this serverside code: */
 Response.Write("<script>var string=");
 yourMethodCall();
 Response.Write("</script>");

 <script>var string=<%: yourMethodCall() %></script>
 /*                   ^ */
 /* Result = */
 <script>var string=outputOfYourMethod</script>
 /* ASP.Net code is translated to this serverside code */
 Response.Write("<script>var string=");
 Response.Write(HtmlEncode(yourMethodCall()));
 Response.Write("</script>");

And, if this is a serverside class, why do you include the $ sign?

Upvotes: 1

Shadow Wizard
Shadow Wizard

Reputation: 66388

You need to wrap this with quotes and replace the double quotes with the proper escape sequence as well:

var string = "<%=SomeClass.SomeMethod("asdada").Replace("\"", "\\\"")%>";

Upvotes: 0

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

You may put the method to create/register client script dynamically in Page_Load, and check if the page is a postback or not in the Page_Load, and if it's not, run the register script code.

Upvotes: 1

Related Questions