简体   繁体   中英

How to set dynamic id with getElementById with c# variable

I'm trying to use the document.getElementById with a dynamic variable.

The dynamic variable will be set based on a query string that is read in from the code behind (c#) in the URL.

So for example, this would be the ideal way it works:

c# code behind:

string myVar = Request.QueryString[0];
myVar = myVar + "Link";

JavaScript:

<script>
    document.getElementById(myVar)
</script>

Any idea on how to get this to work?

You could simply insert this in a script block on your .aspx page (note, avoid using "var" as the name, as that is a reserved word in Javascript):

<script>
    var id = '<%= HttpUtility.JavaScriptStringEncode(Request.QueryString[0]) + "something" %>';
    document.getElementById(id);
</script>

You could inject it into the page from code behind by using RegisterStartupScript :

Page.ClientScript.RegisterStartupScript(this.GetType(), "QueryId", 
    string.Format("<script>var id='{0}';</script>", 
        HttpUtility.JavaScriptStringEncode(Request.QueryString[0]) + "something"
    )
);

The thing is that you cannot just communicate with Server-Side using JS, JS is a client side, so you won't get the variables that you created in ServerSide.

To get them, you'll require:

<%= write_the_thing_here %>

For your code, you'll write:

string someThing = "<%= HttpUtility.HtmlEncode(Request.QueryString[0]) %>";
// now use this someThing in the document..you can use var instead of string
// but not them both..
document.getElementById(someThing); 
// note the semicolon on the end, to close it..

You should not use string var because they are the data types in JavaScript as well as ASP.NET, so code might get puzzled thinking what the hell is this.

Instead of this, you can also try to write a hidden input field as

<input type="hidden" name="someThing" value="@Request.QueryString[0]" />

Then use it to do what ever you want to do dynamically. This might be the easy way of doing this, if you really want to use the ID from the server.

Sorry about the jQuery buddy:

var someThinge = $('input[type="hidden"]').val();

And then, continue your work!

Help note by Alexei Levenkov : semicolons in JavaScript are optional. They main use is to distinguish if code written by obfuscators/minimizers (tools or people) or normal developers :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM