Wednesday, June 29, 2011

Get Current User in Javascript (using Code behind)


Code behind:

protected string username;
protected void Page_Load(object sender, EventArgs e)
{
username = System.Web.HttpContext.Current.User.Identity.Name;
username = username.Replace("\\", "\\\\"); // not a very elegant hack
}
Points to note:
- variable "username" must be at least protected
- need to hack the username because javascript will strip the "\"

Javascript:

var userID = "<%=username %>";
Points to note:
- must put the <%= … %> in quotes

No comments:

Post a Comment