简体   繁体   中英

How to fetch data about current user in ASP .NET MVC?

So, I added a new Parameter to my ApplicationUser class, which is called SocialName . I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference . Do you have any ideas how to do this?

You can easily display info about user in partial view by Html.Action() method without passing info to every action. For example:

Your page/layout/...:

<ul class="nav navbar-nav navbar-right">
    @Html.Action("HeaderUserInfo", "Common")
</ul>

CommonController.cs:

public ActionResult HeaderUserInfo()
{
    var user = _workContext.CurrentUser; //get info about user
    var model = new HeaderUserInfoModel
    {
        Username = user.Username,
        UserId = user.Id
    };
    return PartialView(model);
}

and partial view HeaderUserInfo.cshtml:

@model Models.Common.HeaderUserInfoModel

<span><i class="icon fa fa-user"></i> @Model.Username</span>    

You can get the user from this code:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You can have this in your controller or view then user with all properties will be available for you.

Hi Here is the link to solve your problem exactly. Its seems that you can get the output by using the simple extension method.

Kindly follow the below link , in that asker had a same problem and finally provided the good solution. Hope it will be helpful for you too.

https://forums.asp.net/t/1957500.aspx?How+to+access+custom+Identity+or+ApplicationUser+properties+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM