How to set default value using data annotation

I am learning ASP.Net MVC 5 and I want to set a default using data annotation for a boolean property. Also I don't want to use the constructor to set the default. Is it possible?

public class BalanceDetailMV
{
    public BalanceDetailMV()
    {
        this.isUnitNoEmptyInAllRow = true; // I do not want this
    }
    public bool isUnitNoEmptyInAllRow { get; set; }
}

      

My attmept:

[DefaultValue("true")]
 public bool isUnitNoEmptyInAllRow { get; set; }

      

But the above doesn't work. Please guide me.

+3


source to share


2 answers


If you are using C # 5 or earlier you need to do it through the constructor, but with C # 6 you can do it like this:



public class BalanceDetailMV
{
    public bool isUnitNoEmptyInAllRow { get; set; } = true;
}

      

+6


source


You might get an error if you forgot to add using System.ComponentModel;

to the beginning of the file where you are using the annotation DefaultValue

.

To use bool



[DefaultValue(true)] 
public bool isUnitNoEmptyInAllRow { get; set; }

      

+1


source







All Articles