Reputation: 55
I've gone through many SO threads about this and I've found a way that works (@UserManager.FindByNameAsync(UserManager.GetUserName(User)).Result.Email)
however, I need the email to be assigned to a variable within the code for the page so that I can use it for something else and the class for this isn't a controller class so i'm looking to do this outside the controller.
I'm getting an error that Object reference not set to an instance of an object.
on the Email address: @user.Email
line within the View when I run it and when changing the return type of the Index() function in HomeController to PrescriptionModel I get the error There is no argument given that corresponds to the required formal parameter 'logger' of PrescriptionModel.PrescriptionModel(ILogger<PrescriptionModel>
Upvotes: 0
Views: 4606
Reputation: 252
Using the model to retrieve any data looks very bad in case of MVC pattern. A better way, if you don't want to touch your controller - use code blocks in your view. for example :
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@{
var usr = await UserManager.GetUserAsync(User);
var email = usr?.Email;
}
After that you can render the variable in your view
<li class="email">
<label asp-for="userEmail">@email</label>
<input asp-for="userEmail" class="form-control" disabled />
</li>
The best way to get data to the view is to assign it in controller and pass it to the view in the model.
If this way is not suitable for you - please explain why and we can find the right solution.
The best way, and how MVC implementation must work: All data comes from the controller with the use of strongly typed Views:
public class HomeController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
public HomeController (UserManager<IdentityUser> manager)
{
_userManager = manager;
}
public async Task<IActionResult> Index()
{
var usr = await _userManager.GetUserAsync(HttpContext.User);
return View(new UserModel { Email = usr?.Email });
}
Where model is:
public class UserModel
{
public string Email { get; set; }
}
So you just query all the information that you need in the controller action/index and pass it to the view with your model. This allows you to have different purpose files. Controller for the data manipulatuion/businesss logic Model just DTO to pass values. View to render it. Check this to have more detailed information: https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-3.1
Upvotes: 4