Search code examples
c#.netasp.net-mvcef-code-firstasp.net-identity

How can I retrieve values from the database from a specific users?


I want to be able to retrieve values from the database from a specific user, which in this case @Model.user.Xp, it does not work, I just get 0.

@model TheQuizR.Models.IndexViewModel

@using Microsoft.AspNet.Identity

<div class="row">
    <div class="col-sm-6 col-md-6">
        <ul class="list-group">
            <div class="blue">
                @User.Identity.GetUserName()<br />
        </div>
        <li class="list-group-item">
            Title
            <span class="badge">@Model.user.Xp</span>                                   
        </li>
        <li class="list-group-item">

In the IndexViewModel I have this:

public class IndexViewModel
{

    public ApplicationUser user = new ApplicationUser();

    public bool HasPassword { get; set; }
    public IList<UserLoginInfo> Logins { get; set; }
    public string PhoneNumber { get; set; }
    public bool TwoFactor { get; set; }
    public bool BrowserRemembered { get; set; }

}

In the ApplicationUser class I have all the properties:

public class ApplicationUser : IdentityUser
{
    [MaxLength(128)]
    public string Title { get; set; }
    [Range(0, 5000000)]
    public int Xp { get; set; }
    [Range(0, 100000)]
}

I cant get the id and the username thru Microsoft.AspNet.Identity (the one mark in yellow). I can't get all the other properties.

1


Solution

  • I would recommend to find the user in controller. Then you can create another model or use Viewbag.

    string username = User.Identity.GetUserName();
    var user = db.Users.First(u => u.UserAD == username);
    ViewBag.userIDconnected = user.ID;
    

    View -

    <div class="row">
    <div class="col-sm-6 col-md-6">
        <ul class="list-group">
            <div class="blue">
        </div>
    
        <li class="list-group-item">
            Title
            <span class="badge">@ViewBag.userIDconnected</span>                                   
        </li>
        <li class="list-group-item">