I am new one at that type development and I'm wondering how can I get related data.
I have 2 tables AspNetUsers
and Accounts
. In Accounts
table there are only 3 columns Id
, UserId
join AspNetUsers
table, and Amount
. So, what I want to do, is just get this account information for current logged in user.
I was trying something that I have found in documentation, it works, but shows strange result:
Index.cshtml
:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@{
var user = await UserManager.GetUserAsync(User);
}
@if (SignInManager.IsSignedIn(User))
{
<div >
<h1 >Welcome back, @(user.Email.Split("@")[0])</h1>
</div>
<div>
<h5>Your balance: @Html.DisplayNameFor(model => model.account)</h5>
</div>
}
else
{
<div >
<h1 >Welcome, new one here? Go on and create account!</h1>
</div>
}
Index.cshtml.cs
:
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly WebBankDbContext _context;
private readonly UserManager<IdentityUser> userManager;
private readonly SignInManager<IdentityUser> signInManager;
public IdentityUser user;
public Account account;
public IndexModel(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager, ILogger<IndexModel> logger, WebBankDbContext context)
{
_logger = logger;
_context = context;
this.userManager = userManager;
this.signInManager = signInManager;
}
public async Task OnGetAsync()
{
if (signInManager.IsSignedIn(User))
{
user = await userManager.GetUserAsync(User);
account = (from st in _context.Accounts where st.UserId == user.Id select st).First();
}
}
}
I was debugging this code with breakpoints and had found, that there is correct information in account
, but on page it shows like this:
Your balance: account
What's wrong? How can I fix this? Thanks.
CodePudding user response:
DisplayNameFor
displays name for the model (also your value is in account.Amount
, not just account
).
Just change to:
<h5>Your balance: @(Model.account.Amount)</h5>