I am creating a form for an assignment where when the form is completed the data entered for each applicant is saved to a DB. Each property for the applicants is created in a Applicant class, some are required some not.
As part of this I need to ask the user to enter the gender of the applicant. What I had initially thought to do and implement was create a checkbox for each gender in my form and dependent on which one is checked in my page model I then save that gender back to the Gender property of my Applicant.cs which is a string. When the OnPost() is run.
This works fine but the Gender property must be Required and when I set the prop to Required in the class and run the application, when I try to submit the form I get an error on the page stating the Gender is required.
What is the best way for me to code this in this case or should I think about an alternative solution altogether? I know I could just get the user to type in the gender in a text box and it will work but I thought a group of checkboxes would be neater.
Thanks in advance,
If you want the user to make one choice from a very limited number of options, the best control is the input type="radio"
. This also has the benefit of working well with Razor Pages validation.
Here is your PageModel
property:
[BindProperty, Required]
public string Gender { get; set; }
And here is your form:
<span asp-validation-for="Gender"></span>
<form method="post">
<input type="radio" asp-for="Gender" value="Male" />Male<br />
<input type="radio" asp-for="Gender" value="Female" />Female<br />
<input type="radio" asp-for="Gender" value="Other" />Other<br />
<input type="submit"/>
</form>