how to use enum with DescriptionAttribute in asp.net mvc

前端 未结 4 1455
故里飘歌
故里飘歌 2021-02-07 06:02

I am new to asp.net MVC. I am trying to use dropdown control on my view page, which populates from enum. I also want to add custom descriptions to dropdown values. I searched so

4条回答
  •  暖寄归人
    2021-02-07 06:39

    There is no need to create a helper class if you're using .Net Framework 4.0 or newer.

    You can just use the Display attribute in conjunction with EnumDropDownListFor

    public enum SearchBy
    {
        [Display(Name = "SID/PID")]
        SID = 1,
        [Display(Name = "Name")]
        Name,
        [Display(Name = "Birth Date")]
        DOB,
        [Display(Name = "Cause#")]
        Cause
    }
    

    In your View:

    @Html.EnumDropDownListFor(model => model.SearchBy, "Search By", new { @class = "form-control" })
    

    Microsoft documentation:

    https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.displayattribute?view=netframework-4.8

提交回复
热议问题