How to retrieve logged in username and display in View

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

I am using Identity default of ASP.NET MVC.

So I thought I'd put in 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 Razor.

  • is it correct to use @Html.LabelFor?

At the beginning of the page, I set:

@model OneeWeb.Models.ApplicationUser
@{
    ViewBag.Title = "Index";
}
  • this is the model responsible for having user data?
Author: Thomas Erich Pimentel, 2016-11-09

1 answers

Do not need to set this model in the View (not for this).

To access the user's UserName , just put the code directly in the View, like this:

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

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

The point about not having to use @Html.LabelFor is that it is not something mandatory in Razor. So much so that you can access any model property using @Model.NomeDaPropriedade, by example:

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


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

Or Html.LabelFor is nothing more than a"good practice".

 5
Author: Randrade, 2016-11-09 13:35:57