Search code examples
radio-buttonasp.net-core-mvctag-helpersasp.net-core-tag-helpers

Input radio buttons in ASP.NET Core MVC with taghelpers


I am trying to create a form with a radio button with two values : Automatic and Manual.

In order to do so I adapted an answer to a GitHub issue to my code but unfortunately I have an issue in the line foreach of the View where "Model.GearingType" is not recognized and if I change it to "GearingType" it's not recognized either.

Thanks !

enter image description here

enter image description here

ViewModel

public class EvaluationForm
{
   public enum GearingType
   {
       Manual,
       Automatic
   }

   [Required(ErrorMessage = "Please select your car gearing's type")]
   [Display(Name = "Gearing Type")]
   public GearingType SelectedGearingType { get; set; }

View

<div class="row">
    <div class="col-md">
        @{
            foreach (Model.GearingType gearType in Enum.GetValues(typeof(Model.GearingType))
            {
                <label>
                    <input asp-for="SelectedGearingType" type="radio" value="@gearType" />
                    @gearType
                </label>
            }

        }
    </div>
</div>

Solution

  • You need to specify the Type, not the instance of the model in the typeof statement

    foreach (var gearType in Enum.GetValues(typeof(EvaluationForm.GearingType)))
    {
        ....
    }