0

I'm trying to get the user's name and surname from active directory using the following code:

Default.aspx.cs:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // get the user's name from active dirctory
        var user = UserPrincipal.Current;

        string firstName = user.GivenName;
        string lastName = user.Surname;
    }
}

Default.aspx:

<p class="text-center"><strong><% =firstName =lastName %></strong></p>

However, I get an error saying the variables do not exist in the current context.

I have tried putting public in front of the two strings, but then I get an error saying it's an invalid expression term.

Any suggestions would be great, thank you

Nick
  • 3,745
  • 20
  • 56
  • 75

1 Answers1

4

Your variables are scoped locally to just that one method. In order for an inheriting object (the page) to see them, they need to be protected (or above) class-level members. Something like this:

protected string FirstName { get; set; }
protected string LastName { get; set; }

Then in your method:

protected void Page_Load(object sender, EventArgs e)
{
    // get the user's name from active dirctory
    var user = UserPrincipal.Current;

    FirstName = user.GivenName;
    LastName = user.Surname;
}

And on the page:

<p class="text-center"><strong><% =FirstName %> <% =LastName %></strong></p>
Nick
  • 3,745
  • 20
  • 56
  • 75
David
  • 208,112
  • 36
  • 198
  • 279