1

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?

2
  • did you try $(Document).ready( function { var string = $someclass.somemethod(); }); Commented Jul 20, 2011 at 9:52
  • 1
    Seperation of concerns state this is bad practice. Commented Jul 20, 2011 at 10:07

3 Answers 3

1

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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("\"", "\\\"")%>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.