1

I've been trying to pass an ASP.NET variable to a javascript function without any luck so far.

What I have is:

A master page that is using several .js files under folder root/js

I'm trying to create a public variable that contains the username of a person and would like to send it to a function that is inside one of the js files mentioned above.

public string username;
...
username = User.Identity.Name.ToString();

my js is:

$(document).ready(function {

var username = "<%= username %>";

var element = document.getElementById("userid");

element.innerHTML = username; });

After executing this I get <%= username %> and not the actual value.

I tried a second approach:

ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "customScript", "AssignValue('" + username + "');", true);

but I get function (e,t){return new x.fn.init(e,t,r)} as a result... I don't know what to do.

Any ideas will be highly appreciated!

Thank you!

5
  • 1
    In which file is the assignment happening? (var username = "<%= username %>";) Commented Nov 12, 2013 at 22:44
  • you have to put assignment in the aspx file corresponding to the cs file which contains the username variable.In the worst case you can assign it to a hidden variable with run at server enabled. Commented Nov 12, 2013 at 22:48
  • It's in the Default.aspx file. I declare and assign the variable in the corresponding cs file for the aspx page just mentioned. Commented Nov 12, 2013 at 22:50
  • Is the JavaScript function within the ASPX page or an external JavaScript file? Commented Nov 12, 2013 at 23:32
  • It's an external JavaScript file Commented Nov 12, 2013 at 23:33

1 Answer 1

1
// aspx
<asp:HiddenField runat="server" ID="hfUserName" />

// page_load:
hfUserName.Value = username;

// js
$(function() {
   $("#userid").text($("input[id$='hfUserName']").val());
});
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do it without a hidden field?

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.