16

I am learning ASP.Net MVC 5 and I want to set default value using data annotation for boolean property. Also I don't want to use the constructor to set the default value. 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 above does not work. Please guide me.

Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • 1
    `DefaultValueAttribute` is not used by MVC. You need to set it in a constructor (or when you initialize your model) –  Jun 16 '17 at 14:25
  • Even if it were set like this, in C# "true" is a **string** and NOT a boolean. – oerkelens Jun 16 '17 at 14:26
  • @oerkelens: you are right. Actually I did put a bool true there. But it had compile time error and all. So, as a beginner I did some experimentation. – Unbreakable Jun 16 '17 at 14:28

2 Answers2

26

If you're using C# 5 or earlier, you have to do it through the constructor, but since C# 6, you can do it like this:

public class BalanceDetailMV
{
    public bool isUnitNoEmptyInAllRow { get; set; } = true;
}
FF-
  • 732
  • 9
  • 19
15

You might be having error if forgot to add using System.ComponentModel; at the top of your file where you use DefaultValue annotation.

For bool use

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