rabyusbeef
rabyusbeef

Reputation: 11

Get Current Logged Username in my app

I would like to get the current logged in username and display it my frontend. Currently I have a function called GetCurrentUser() that gets called when a button is clicked.

<button type="submit" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; "value="Submit">Save Selections</button><br>

function GetCurrentUser() {
var usrName ="@HttpContext.Current.User.Identity.Name.ToString()";
//var usrName = '<%HttpContext.Current.User.Identity.Name %>';
//document.getElementById("UserName").innerHTML = usrName;
console.log(usrName);}

I get the follwoingoutput in my console log--> @HttpContext.Current.User.Identity.Name

Upvotes: 0

Views: 13253

Answers (2)

Josue Barrios
Josue Barrios

Reputation: 502

I could get the user logged in by passing the script at the end of the document.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Example.SiteMaster" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
    <form runat="server">
    </form>
    <script>
        var loggedUser = "<%: HttpContext.Current.User.Identity.Name %>";
    </script>
</body>
</html>

I hope you find it useful.

Upvotes: 1

Travis Acton
Travis Acton

Reputation: 4430

If you are seeing the literal output of "HttpContext.Current.User.Identity.Name " then your JS function is generated client side after you have lost server context.

Couple options for you:

  1. Call back to your controller via ajax to get the username

  2. Store the username in a read only field on page load (kinda like setting a form value) and retrieve the value via jquery or js on function call

  3. Assign the username on page load to a global js element and just use that element in your function.

Here is an example of 2 and 3. I don't think you should worry about #1 until you fully understand why your issue is happening in the first place:

    <div class="btn btn-info" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; " value="Submit">Save Selections</div><br>
    <input type="hidden" name="method2" id="method2" value="@System.Security.Principal.WindowsIdentity.GetCurrent().Name">
    @section scripts {
        <script>
            var globalSettingMethod = '@System.Security.Principal.WindowsIdentity.GetCurrent().Name';
            function GetCurrentUser() {
                alert(globalSettingMethod);
                alert($('#method2').val());
            }
        </script>
    }

Upvotes: 2

Related Questions