Default value in mvc model using data annotation

前端 未结 5 1482
小鲜肉
小鲜肉 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:45

    You can only do this using the class' constructor. Your code should thus look like this:

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

    This will lead to the MyId property being set to 1 whenever a new instance of the class is made. However, if model binding detects that the user has specified a value for MyId, it will overwrite the default value with the user-specified one.

提交回复
热议问题