Is it possible using data annotations to add default value for int property
something like
[DefaultValue=1] public int MyId {get; set;}
In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.
ComponentModel. DataAnnotations) Specifies that a data field value is required.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
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; }
Use [DefaultValue(false)]
.
(Reference)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With