locked
how to use Enum field in Controller Model and apply required field validation RRS feed

  • Question

  • User1838940990 posted

    Hi All,

    We are working on a new asp.net core web api.

    We have a person model with one field Occupation which is a Enum, its throwing error in swagger and , if I change to string ,no error.

    is there any way  I can use the enum as model field and apply  required field validation that, user can only enter the values matching to the enum

    Please see the model, enum and controller class below for your reference , if this is not the best approach, can you please suggest  other best approach which can be used for a enterprise Api 

    Thanks in Advance and good weekend.

    [HttpPost]
            public IActionResult Calculate(PolicyHolder policyHolder)
            {
                return Ok("Calculated Successfully");
            }
    
    
    public class PolicyHolder : IPerson
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public DateTime DateOfBirth { get; set; }
           public Occupation Occupation { get; set; }
      }
    
        public enum Occupation
        {
            Cleaner,
            Doctor,
            Author,
            Farmer,
            Mechanic,
            Florist
        }

    Friday, April 30, 2021 6:01 AM

All replies

  • User503812343 posted

    change your model to use validation attribute.  for more details see asp.net mvc validation attribute with enum

    public class PolicyHolder : IPerson
        {
            
    	[EnumDataType
                (typeof(Occupation))]        
           public Occupation Occupation { get; set; }
      }
    

    Friday, April 30, 2021 12:01 PM
  • User1655654435 posted

    I also had this problem. I solved it by using a string, because then validation is easier. Then in the controller i save it as an enum in the database by converting the string to enum.

    Friday, April 30, 2021 12:16 PM