I am using the Intranet template for MVC 4 under the VS 2012 RC. The top right hand corner shows domain\username, and I want it to show full name instead.
I was able to get this working in _Layout.cshtml. I included the following helper in the body –
@helper AccountName()
{
using (var context = new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain))
{
try
{
var principal = System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(context, User.Identity.Name);
@String.Concat(principal.GivenName, " ", principal.Surname)
}
catch { }
}
}
(I also had to include System.DirectoryServices.AccountManagement in the References)
I could then use the helper in the greeting code as follows –
<section id="login">
Hello, <span class="username">@AccountName()</span>!
</section>
This works ok, but I don’t like having the code in the _Layout.cshtml. I tried to put the helper in a seperate file under a Helpers directory, but @AccountName() no longer resolved then. Ideally the code should really be in a straight CS file.
Can anyone suggest a better way to set this up?
You can certainly put the code in a regular C# file, e.g.
In that case, you need to include the namespace your helpers are in by placing
at the top of any view that wants to reference that code.
Alternatively, you can make that namespace available to all views by editing the
web.configfile in the Views directory (not the one at the project level)