How to recover logged in user name and display in View

Asked

Viewed 691 times

4

I’m trying to develop a page, where after the user login, it is redirected to an index, where I would like to display the user name.

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

So I thought I’d put it on view the following code:

                <!-- 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>

But I’m having a hard time using that Razor.

  • It is correct to use @Html.LabelFor?

At the beginning of the page, I defined:

@model OneeWeb.Models.ApplicationUser
@{
    ViewBag.Title = "Index";
}
  • This is the model responsible for having user data?
  • If you want to show a value other than Identity.Name, advise that I extend the answer.

  • Not the idea is really Name, but I did not understand why I can use direct @User.Identity.Name

1 answer

5


No need to define this model in the View (not for this).

To access the Username user, just put the code directly in the View, this way:

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

The fact that you can directly use Identity is that this is a property of the Iidentity interface.

The question of not having to use the @Html.LabelFor is that it is not a must on Razor. So much so that you can access any Model property 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 Html.Labelfor is nothing more than a "good practice".

  • Perfect, it worked, but now I got lost, can explain to me why in this case I use direct @User.Identity.Name

  • 1

    @Thomaserichpimentel Get better now

Browser other questions tagged

You are not signed in. Login or sign up in order to post.