How to retrieve user name logged in and display in View

4

I am trying to develop a page, where the user is logged in, he is redirected to an index, where he would like to display the user name.

I'm using Identity default of ASP.NET MVC .

Then I thought about putting the following code in view :

                <!-- menu profile quick info -->
                <div class="profile">
                    <div class="profile_pic">
                        <img src="~/images/img.jpg" alt="..." class="img-circle profile_img">
                    </div>
                    <div class="profile_info">
                        <span>Seja Bem vindo,</span>
                        <h2>@Html.LabelFor(m => m.User.Identity.Name)</h2>
                        @*<h2>John Doe</h2>*@
                    </div>
                </div>

However, I'm having trouble using this Razor .

  • Is it correct to use @Html.LabelFor ?

At the beginning of the page, I defined:

@model OneeWeb.Models.ApplicationUser
@{
    ViewBag.Title = "Index";
}
  • Is this the model responsible for having the user data?
asked by anonymous 09.11.2016 / 14:10

1 answer

5

You do not need to set this model in View (not for this).

To access the UserName user, just put the code right in the View, like this:

<h2>@User.Identity.Name</h2>

The fact that you can use Direct is that Identity, that is a property of the IIdentity interface .

The issue of not having to use @Html.LabelFor is that it is not mandatory in Razor. So much that you can access any property of the Model using @Model.NomeDaPropriedade , for example:

@model OneeWeb.Models.Produto
@{
    ViewBag.Title = "Index";
}


 <h2>@Html.LabelFor(m => m.Titulo)</h2>
 //ou
 <h2>@Model.Titulo</h2>

The # is nothing more than a "good practice".

    
09.11.2016 / 14:22