Reputation: 25
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!
Upvotes: 1
Views: 77
Reputation: 995
// aspx
<asp:HiddenField runat="server" ID="hfUserName" />
// page_load:
hfUserName.Value = username;
// js
$(function() {
$("#userid").text($("input[id$='hfUserName']").val());
});
Upvotes: 1