1

Upon each login in ASP.NET I place the users username in the session like this

//..... 
if (PasswordHash.PasswordHash.ValidatePassword(LoginForm.Password, password))
{
    e.Authenticated = true;
    Session["Username"] = LoginForm.UserName;
}
//.....

Now I need to access that through JS and I thought I could just do this:

    if (won) {
        var username = '<%= Session["Username"] %>'
        alert("Congrats " + username + ", you won!");
    }

But I'm getting Congrats <%= Session["Username"] %>, you won! instead. Why is that? Judging by answers in this and this question I should be able to access it like that.

Community
  • 1
  • 1
MrPlow
  • 1,295
  • 3
  • 26
  • 45
  • 3
    Are you using `<%= Session["Username"] %>` in JS file? It won't work there – Satpal Dec 24 '13 at 15:51
  • @Satpal yes I am. I see. Now that I think of it it makes sense that it wouldn't work in the .js file. I guess I have to use Ajax – MrPlow Dec 24 '13 at 16:29

2 Answers2

2

You can encode your username into a div or a javascript variable.

Add this to the page where you are calling your javascript from

<div id="userinfo" data-user-name="<%= Session["Username"] %>">

and then read the data by using jquery

$('#userinfo').data('user-name')

For javascript add the following to your page

<script>
 var username = "<%= Session["Username"] %>";
</script>

And then you can use your variable in other parts of the code.

Marko
  • 2,734
  • 24
  • 24
1

I can suggest to use something like this:

        if (won) {  
         $.ajax({
                   type: "POST",
                   url: "SomePage.aspx/GetUserName",        
                   contentType: "application/json; charset=utf-8",
                   dataType: "text",
                   success: function (name) {
                      alert("Congrats " + name+ ", you won!");        
                   }
               });
        }

    [System.Web.Services.WebMethod]
    public static string GetUserName()
    {
    ...
      if (PasswordHash.PasswordHash.ValidatePassword(LoginForm.Password, password))
      {  
         return LoginForm.UserName;
      }
    ...
    }
Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68
  • for doing ajax call to aspx web method should be static. And question is get UserName from Session object... – Mehmet Dec 24 '13 at 21:13