I am creating a ASP.NET Core 3.1 Application. I have added "Buyer" and "Seller" roles. How can I add the option for the user to chose one of them when registering.
Thank you in advance.
I managed to find a solution that needs some adjustments, but for the time being works for me. So here is what I did:
1.1 Right click on your project name -> select "Add" -> "New Scaffolded Item".
1.2 On the "Add New Scaffolded Item" tab select "Identity" (on the left side). -> In the middle of the tapp click on "Identity". -> Press "Add". 1.3 From the "Add Identity" tab check the box next to "Account/Register". -> From the "Data context class" drop down list select "ApplicationDbContext ([ProjectName].Data)". -> Click "Add".
2.1 Firstly I added a new property to the RegisterModel class, that stores List.
public List<SelectListItem> Roles { get; }
2.2 Then in the constructor I create the List.
Roles = new List<SelectListItem>
{
new SelectListItem {Value = "Seller", Text ="Seller"},
new SelectListItem {Value = "Buyer", Text = "Buyer"},
};
2.3 After that I added the following property to the InputModel class, located within the RegisterModel
[Required]
[Display(Name = "UserRole")]
public string UserRole { get; set; }
2.4 The last thing I did here was editing the OnPostAsync method. In the code block checking if the creation of the user was successful
if(result.Succeeded)
I added the following line :
await _userManager.AddToRoleAsync(user, Input.UserRole);
3.1 Just under the code for the "ConfirmPassword" field
<div class="form-group">
<label asp-for="Input.ConfirmPassword"></label>
<input asp-for="Input.ConfirmPassword" class="form-control" />
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
</div>
I added the code that creates the drop-down list, used by the user to chose his role
<div class="form-group">
<select asp-for="Input.UserRole"
asp-items="@(Model.Roles)">
<option>Please select a role</option>
</select>
<span asp-validation-for="Input.UserRole" class="text-danger"></span>
</div>