Default value in mvc model using data annotation

前端 未结 5 1530
小鲜肉
小鲜肉 2020-12-29 18:01

Is it possible using data annotations to add default value for int property

something like

[DefaultValue=1]
public int MyId {get; set;}
5条回答
  •  余生分开走
    2020-12-29 18:54

    Try this - set the default value in the constructor:

    public class YOURMODEL
    {
        public int MyId { get; set; }  
    
        public YOURMODEL()
        { 
            MyId = 1;       
        }
    }
    

    Later addition by other user: Since C# 6.0 (2015) this simpler syntax has been allowed:

    public class YOURMODEL
    {
        public int MyId { get; set; } = 1;
    }
    

提交回复
热议问题