Rui Ruivo

Rui Ruivo

  • NA
  • 132
  • 37.3k

Model enums to form select dropdown menu

Jul 2 2023 5:05 PM

Good morning

I have a model with some options as enums that i want to appear in the form automaticly. How ?

"CampaignType" and "CampaignStatus"

I tryed to add:

asp-items="Html.GetEnumSelectList<CampaignType>()"

But VS2022 didn't like it.

My Model:

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;

namespace HyperWeb_V3.Models
{
    public class MarketingCampaign
    {

            .
            .
            .

        [Required(ErrorMessage = "Please select the type of campaign.")]
        public CampaignType Type { get; set; }

        [Required(ErrorMessage = "Please select the status of the campaign.")]
        public CampaignStatus Status { get; set; }

            .
            .
            .

    }

    public enum CampaignType
    {
        Advertisement,
        Email,
        Webinar,
        Conference,
        Other
    }

    public enum CampaignStatus
    {
        Planned,
        InProgress,
        Completed
    }

}

My Form:
 

          .
          .
          .

        <form method="post">

          .
          .
          .

            <div class="form-group">
                <label asp-for="MarketingCampaign.Type" class="control-label"></label>
                <select asp-for="MarketingCampaign.Type" asp-items="Html.GetEnumSelectList<CampaignType>()" class="form-control"></select>
                <span asp-validation-for="MarketingCampaign.Type" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="MarketingCampaign.Status" class="control-label"></label>
                <select asp-for="MarketingCampaign.Status" class="form-control"></select>
                <span asp-validation-for="MarketingCampaign.Status" class="text-danger"></span>
            </div>
             
          .
          .            
          .

        </form>

Best regards
Rui Ruivo


Answers (1)