Developer technologies | ASP.NET | ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I've cobbled together a functioning radio button in a view from what I could find online. I'm using the value of true to indicate one thing, false another thing, and empty for a third.
It works but I am curious about three things...
<div class="form-group">
<label asp-for="Bool01" class="control-label"></label>
<label>
<input type="radio" asp-for="Bool01" value="true" /> True
</label>
<label>
<input type="radio" asp-for="Bool01" value="false" /> False
</label>
<label>
<input type="radio" asp-for="Bool01" value=" " /> None
</label>
</div>
<br />
<div class="form-group">
<label asp-for="Bool01" class="control-label"></label>
<input asp-for="Bool01" class="form-control" />
<span asp-validation-for="Bool01" class="text-danger"></span>
</div>
Here is an example using Bootstrap using Razor Pages, will work with your project too.
public enum GenderTypes
{
Male,
Female,
Unspecified
}
Backend
public class RadioButton2Model : PageModel
{
/// <summary>
/// Get a random gender
/// </summary>
public void OnGet()
{
var values = Enum.GetValues(typeof(GenderTypes));
Random random = new();
GenderTypes gender = (GenderTypes)values.GetValue(random.Next(values.Length))!;
Gender = gender.ToString();
}
/// <summary>
/// Other option, an enum
/// </summary>
[BindProperty]
public string? Gender { get; set; }
public Person Person { get; set; } = new ();
public string[] Genders = Enum.GetNames(typeof(GenderTypes));
public void OnPost()
{
ViewData["Selected"] = Gender;
if (Enum.TryParse(Gender, true, out GenderTypes gender))
{
Person.Gender =gender;
}
Log.Information("Selection is {P1}", Gender);
}
}
View
<div class="container mt-4">
<form method="post" tabindex="0">
<div>
@foreach (string gender in Model.Genders)
{
<div class="form-check form-check-inline">
<input class="form-check-input" type="">
<input type="radio"
class="form-check-input"
asp-for="Gender"
value="@gender"
aria-description="@gender"
id="Gender@(gender)" />
<label class="form-check-label" for="Gender@(gender)">@gender</label>
</div>
}
</div>
<div>
<input type="submit" value="Submit" class="btn btn-primary mt-2" aria-description="submit your response" />
</div>
</form>
</div>
The default binding for bool is a checkbox. If you need 3 values then your options are a select or radio list.
bootstrap has several formatting options
https://getbootstrap.com/docs/5.0/forms/checks-radios/
once you decide, you could make a tag helper.