0
 var nUserID = '<% if (ids != null) {ids.userID.ToString();}%>'

Note: ids is not null nor ids.userID is null but em getting nUserID = ""
Is there any way to convert C# string to Javascript string?

1
  • 1
    You should not think of this as "converting a C# string to a Javascript string". Such a thing does not make sense .. the two never interact in this scenario where the page is being rendered. Your C# is merely being interpreted and the result dumped into the HTML. Commented Feb 6, 2015 at 10:20

4 Answers 4

3

For write it direct on page you need to use the Response.Write as

 var nUserID = <% if (ids != null) {Response.Write(ids.userID.ToString());}%>

beside that, if you need to add at the end ; or place it inside quotas is up to you.

The <% %> did not write on page, just run the code.
The <%= %> write on the page as the Response.Write

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

3 Comments

...or just have it evaluated for you with: var nUserID = "<%= ids.userID %>"
@SimonWhitehead But if the user need some check for null ?
Touche - I completely disregarded that part. My apologies. I would still use <%= %> but wrap the NullRef check in a method :)
0
var nUserID = '<%=((ids != null) ? ids.userID.ToString() : "0")%>';

Comments

0

Use Something Like this:

 <script  type="text/javascript">

   var nUserID = '<%=ids.userID.ToString()%>';

if(!nUserID)
{ 
 //check for null in javascript
alert(nUserID);

}

   </script>

Comments

0

More appropriate solution would be to to save your ids.userID to data attribute of some related html element or just create invisible div element with all C# data you want to use in your javascript code as data attributes. And then use jQuery to extract that data in scripts.

<div id="settings" style="display: none;" data-user-id="<%= ids.userID %>"></div>

and javascript:

var nUserID = $('#settings').data('user-id');

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.