Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value in mvc model using data annotation

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

something like

[DefaultValue=1] public int MyId {get; set;} 
like image 887
user1765862 Avatar asked May 23 '14 07:05

user1765862


People also ask

What is the use of data annotations in MVC?

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.

Which data annotation is used for mandatory model fields?

ComponentModel. DataAnnotations) Specifies that a data field value is required.

What is data annotation in C#?

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.


2 Answers

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; } 
like image 94
Nilesh Gajare Avatar answered Sep 19 '22 10:09

Nilesh Gajare


Use [DefaultValue(false)].

(Reference)

like image 21
bellona Avatar answered Sep 20 '22 10:09

bellona