Cannot display enum values on Kendo grid

后端 未结 2 1712
悲&欢浪女
悲&欢浪女 2020-12-10 23:23

In my MVC5 application I have an enum class as shown below and with this approach I can pass the enum values i.e. US, UK instead of United States\" from Controller to View.

2条回答
  •  旧巷少年郎
    2020-12-10 23:30

    You must set NotMapped attribute for custom property:

    using System.ComponentModel.DataAnnotations.Schema;
    public class VisitorViewModel
    {
        [Key]
        public int VisitorID { get; set; }
    
        public Country Country { get; set; }
    
        [NotMapped]
        public string CountryName
        {
            get { return Country.GetDescription(); }
        }
    }
    

    and GetDescription() is next extension method:

    public static string GetDescription(this Enum e)
    {
        var field = e.ToString();
        var attribute = e.GetType().GetField(field).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
    
        return attribute != null ? ((DescriptionAttribute)attribute).Description : field;
    }
    

提交回复
热议问题