I am trying to show additional fields in the registration form based on the UserRole combobox. Depending on the role I create a different object in the user. Here is my register html:
@page
@model RegisterModel
@{
ViewData["Title"] = "Register";
var roles = (List<IdentityRole>)ViewData["roles"];
Layout = "~/Areas/Identity/Pages/_AuthLayout.cshtml";
}
<h1>@ViewData["Title"]</h1>
<div class="col">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<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>
</div>
</div>
<div class="form-group"><!--This is the checkbox based on which I want to add fields-->
<label asp-for="Input.UserRole"></label>
<select asp-for="Input.UserRole" class="form-control" asp-items='new SelectList(roles,"Id","Name")'>
</select>
<span asp-validation-for="Input.UserRole" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
It is more or less the default login that is generated when creating a new identity. Here is my inputmodel in the register.cshtml.cs:
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Das {0} muss minimum {2} und maximum {1} Zeichen lange sein.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm ")]
[Compare("Password", ErrorMessage = "Die Passwörter stimmen nicht überein.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Rolle")]
public string UserRole { get; set; }//based on this checkbox
}
If the selected role is admin I don't need any additional fields. If the selected role is a, I also need the first name, which should be required then. If the selected role is b, I need first name and second name, both required. I did manage to make my own fields without a problem. I am using asp.net core mvc 3.5.1. Any inputs on how to do this?