How to display First Name and Last Name instead of email _LoginPartial - asp.net-core

am building a web application using ASP.NET CORE 3.0(razor pages), I extended my IdentityUser by adding first name and last name field, and I want display the both fields in place of email in _loginPartial here is my Class
public partial class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
}
Here is where am calling the username
<li>
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello #User.Identity.Name!</a>
<ul>
<li>
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
</ul>
</li>
I am not sure of how to get FirstName and LastName in place of User.Identity.Name.
please I need help.

The simplest way to achieve that is to add it to ViewData like this:
In your Account controller on the Manage index view
// read the application user from db
var user = dbContext.Users...
ViewData["UserFirstName"] = user.FirstName;
ViewData["LastName"] = user.LastName;
And then in your view just read those values from ViewData
<div>
Hello #ViewData["UserFirstName"] #ViewData["UserLastName"]
</div>
Another approach is to add a model to your view; here are some good docs that you can read:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/overview?view=aspnetcore-3.1

Related

ASP.Net Core MVC Passing model to controller empty why?

I have a razor view page which is showing data from my database. I have a submit button which calls the action with the model but in the controller the model is empty. Can some please explain what I am doing wrong? Here is my razor page code:
<div class="row align-items-start mt-4">
<div class="col-12">
<a class="btn btn-primary float-right" asp-controller="CustomerDetails" asp-action="UpdateCustomer" asp-route-customermodel="#Model.customer"><span class="fas fa-plus-circle"></span> Submit</a>
</div>
</div>
Here is my controller code: -
public IActionResult UpdateCustomer(Customer customermodel)
{
if (ModelState.IsValid)
{
customerRepository.update(customermodel);
} else
{
string error = ModelState.Values.ToString();
}
return View("../Home/Index");
}
I found the line of code below which seems to work but again I have to add 50 property names rather than just the model. Seems like this is not the correct approach or I am doing it wrong.
public ActionResult Create([Bind(Include = "CourseID,Title,Credits,DepartmentID")]Course course)
Thanks for any advice,
If you use asp-route-customermodel="#Model.customer",you will get:
<a class="btn btn-primary float-right" href="/CustomerDetails/UpdateCustomer?customermodel=ClientSideDemo3.Models.Customer"><span class="fas fa-plus-circle"></span> Submit</a>
asp-route-xxxcannot bind model,here is a demo:
Model:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
View:
<a class="btn btn-primary float-right" asp-controller="CustomerDetails" asp-action="UpdateCustomer" asp-route-Id="#Model.customer.Id" asp-route-Name="#Model.customer.Name"><span class="fas fa-plus-circle"></span> Submit</a>
result:

How do I route a variable to another page from a select list in Razor Pages

This likely has a simple solution but I've struggled for a while now.
I have a form with a select list, and I want to select an item and then send that item value to a new page using a button in the same form. For some reason I can't figure out how to save the item value, I don't know what I'm missing.
Page 1 html
<form method="post" class="container">
<h4>Generate printable list by lab</h4>
<div class="form-group form-row">
<select asp-for="LabNumberToFilter" asp-items="Model.LabNumberListOptions" class="form-control col-md-2">
<option value="">Select a lab number</option>
</select>
<span asp-validation-for="LabNumberToFilter" class="text-danger"></span>
<a class="btn btn-info btn-lg col-md-2" asp-page="./Page2"
asp-route-labNumber="#Model.LabNumberToFilter" />Create List<a/>
</div>
</form>
Page 1 model
[BindProperty]
public int LabNumberToFilter { get; set; }
public SelectList LabNumberListOptions { get; set; }
public async Task<IActionResult> OnGetAsync() {
(…)
LabNumberListOptions = new SelectList(_context.LabTours, nameof(LabTour.LabNumber), nameof(LabTour.LabNumber));
return Page();
}
Page 2 html
#page "{labNumber:int?}"
(…)
Page 2 model
public int LabNumber { get; set; }
public IList<LabTour> LabTourList { get; set; }
public async Task OnGetAsync(int? labNumber)
{
LabNumber = labNumber.Value;
LabTourList = await _context.LabTours.Where(l => l.LabNumber == LabNumber).ToListAsync();
}
If I put a default value in for my LabNumberToFilter, the button routes the default value correctly, so the problem is that my select list doesn't save/use the new inputted value when I hit the button to redirect to page 2. What did I do wrong?
Specify an action in the form that points to page 2. You can do this either by explicitly setting the action attribute:
<form method="post" action="/Page2">
or by passing the page name to the asp=page attribute:
<form method="post" asp-page="/Page2">
Then in Page2, add the [BindProperty] attribute to a public property with the same name as the parameter specified by the asp-for attribute in the select element (LabNumberToFilter):
[BindProperty]
public int LabNumberToFilter { get; set; }
This will capture the posted value. You don't need the parameter in the handler method, or the route template.
Note that the form's method is Post, so the OnGet handler in page 2 will not execute.
See here for more background on model binding in Razor Pages: https://www.learnrazorpages.com/razor-pages/model-binding
I would suggest using a datalist
You will have to load it in a loop but then you can access the value from the input e.g.
<form method="post">
<input type="text" asp-for="LabNumberToFilter" list="labNumbers" placeholder="Select or enter a lab number"/>
<datalist id="labNumbers">
#foreach (var labNum in Model.LabNumberListOptions)
{
<option value="#labNum"></option>
}
</datalist>
<button type="submit" ...
</form>

ClaimType.GivenName doesn't return my first name

I am developing .net core 2.2 application that authenticates from Azure AD. I would like to get the user's first name in the _LoginPartial.cshtml in RAZOR web app. I am able to get the user's surname and email but not the first name. Is there away to get this?
This is what i have in my login partial view:
Claim nameClaim = User.Claims.FirstOrDefault<Claim>(claim => string.Compare(claim.Type, "name", StringComparison.Ordinal) == 0);
string userName = (nameClaim != null) && !string.IsNullOrEmpty(nameClaim.Value) ? nameClaim.Value : ((User != null) && (User.Identity != null) ? User.Identity.Name : string.Empty);
Also i tried this:
#User.FindFirst(System.Security.Claims.ClaimTypes.GivenName).Value
The given name returns email same as name and email properties!!
What would be the ideal way to get the first name by extending the identity model in asp.net?
For Identity, there is no FirstName in the built-in IdentityUser, you need to implement your own user like:
public class ApplicationUser:IdentityUser
{
public string FirstName { get; set; }
}
Then, implement UserClaimsPrincipalFactory<ApplicationUser>
public class CustomClaimsIdentityFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
public CustomClaimsIdentityFactory(UserManager<ApplicationUser> userManager
, IOptions<IdentityOptions> optionsAccessor)
: base(userManager, optionsAccessor)
{
}
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
//custom claims
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim("FirstName", user.FirstName)
});
return principal;
}
}
Then, you could check the FirstName by #User.Claims.FirstOrDefault(c => c.Type == "FirstName")?.Value like
#using Microsoft.AspNetCore.Identity
#using TestIdentity.Data
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
<ul class="navbar-nav">
#if (SignInManager.IsSignedIn(User))
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello #User.Claims.FirstOrDefault(c => c.Type == "FirstName")?.Value!</a>
</li>
<li class="nav-item">
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
}
</ul>

Asp.net Core, redirect to another view from partial view using form ajax?

I have a Partial view that contains a form ajax in Asp.net core 2.0.
You can see Partial View named _loginPartial
#model partialView.Models.LoginViewModel
<div id="login">
<form asp-controller="Account" asp-action="Login" id="frmLogin" data-ajax="true" data-ajax-method="POST" data-ajax-update="#frmLogin" data-ajax-mode="Replace">
<div id="login">
<div class="form-group">
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName"></span>
</div>
<div class="form-group">
<input asp-for="Password" class="form-control" />
<span asp-validation-for="UserName"></span>
</div>
<div class="form-group pull-left ">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
When i submit form to /Account/Login everything is ok, but after login i want to redirect to another view in another Area
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
//Success Login
return Redirect("/AdminPanel/Home/Index");
}
else
{
//if ModelState is invalid
}
//if UserName Or Password is incorrect
return PartialView("_loginpartialView", model);
}
And here is LoginViewModel
public class LoginViewModel
{
[Display(Name = "UserName")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Please Enter UserName")]
public string UserName { get; set; }
[Display(Name = "Password")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Please Enter Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
Also i use this code to Show Partial View in index
#Html.Partial("_loginpartialView")
But there is a problem. After success login new view replace with Partial view.In other words, it does not navigate to /AdminPanel/Home/Index and new View replace with Partial View, How can i navigate to another view in this case?
As you are dealing with an AJAX callback, you can't do the redirection on server-side. This must be handled on client-side using Javascript.
Examine the response from the server and if it's a redirection then set window.location to the received URL.

How do you display a users full name in the login partial view in ASP.NET Core

I'm new to ASP.NET Core, most of my existing experience is with Java/PHP, and a little ASP.NET MVC about 10 years ago.
I'm using a Mac so I'm trying to build a project using Visual Studio Code and ASP.NET Core.
I've created a web application using 'yo'. I've changed the default database connection string to use an MSSQL database I have on a server. I've ran the dotnet ef database update command to create the necessary tables in the database.
I wanted to add firstname and lastname to the user, so I've created the columns in the AspNetUser table, and edited the ApplicationUser class to reflect this;
namespace pabulicms.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
}
I've gone ahead and amended the view model for the registration form to include the firstname and lastname, and I've updated the Signup method so that the firstname and lastname is saved to the database.
By default the _LoginPartial.cshtml view displays the users username(email address), I'd like to change this to display the users full name, but I'm unsure as to how I do this.
This is what the _LoginPartial looks like at the moment;
#using Microsoft.AspNetCore.Identity
#using pabulicms.Models
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
#if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello #UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
It's obviously this line I need to change;
Hello #UserManager.GetUserName(User)!
However changing it to #UserManager.GetFirstname(User)! doesn't work, as it tells me that the method GetFirstname doesn't exist;
I searched a lot and finally found this solution:
Change this:
#UserManager.GetUserName(User)
To this: #UserManager.GetUserAsync(User).Result.LastName
refer to: Link
ASP.NET Core Identity library uses claims-based approach to Authorization. It means that a logged in user (the one you can access via User object in your views) has some list of claims (name-value pairs) associated with it.
By default, that list contains two claims: for ID and username.
However, it's easy to add to that list any other claim you need (first/last name, the name of the company, current user's balance, etc.).
You will just need to create your own implementation of IUserClaimsPrincipalFactory interface and register it in DI to override the default one.
Here is the article with a step-by-step description how to do it.
You can skip the first part ("zero" part to be more exact) "Preparations" if you already have the additional properties (like FirstName/LastName) in your ApplicationUser class.
In the end I used a view component.
First I created a view component myprojectname/ViewComponents/AccountStatusViewComponent.cs
namespace myprojectname.ViewComponents
{
public class AccountStatusViewComponent : ViewComponent
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
public AccountStatusViewComponent(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
public async Task<IViewComponentResult> InvokeAsync()
{
AccountStatusModel model = new AccountStatusModel();
model.User = _userManager.GetUserAsync(Request.HttpContext.User).Result;
return View(model);
}
}
}
Next I created the view for the view component myprojectname/Views/Shared/Components/AccountStatus/Default.cshtml
#model AccountStatusModel
#using Microsoft.AspNetCore.Identity
#using myprojectname.Models.ViewComponentModels;
#using myprojectname.Models
#inject SignInManager<ApplicationUser> SignInManager
#inject UserManager<ApplicationUser> UserManager
#if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello #Model.User.Firstname #Model.User.Lastname</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
I created a model to hold the data I wanted passing the view in myprojectname/Models/ViewComponentModels/AccountStatusModel.cs
using System;
namespace pabulicms.Models.ViewComponentModels
{
public class AccountStatusModel
{
public ApplicationUser User { get; set; }
}
}
Finally, in the example .NET website I edited the file Views/Shared/_Layout.cshtml and replaced this line;
#await Html.PartialAsync("_LoginPartial")
With;
#await Component.InvokeAsync("AccountStatus")
my simple way :
top of view
#{
#inject UserManager<ApplicationUser> UserManager;
var DisplayName= UserManager.Users.FirstOrDefault(m=>m.UserName==User.Identity.Name).FullName;
}
Hello #DisplayName
ofcourse may it's not be a best way with best performance but worked for me.