Default value in an asp.net mvc view model
Solution 1:
Set this in the constructor:
public class SearchModel
{
public bool IsMale { get; set; }
public bool IsFemale { get; set; }
public SearchModel()
{
IsMale = true;
IsFemale = true;
}
}
Then pass it to the view in your GET action:
[HttpGet]
public ActionResult Search()
{
return new View(new SearchModel());
}
Solution 2:
Use specific value:
[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6
Solution 3:
Create a base class for your ViewModels
with the following constructor code which will apply the DefaultValueAttributes
when any inheriting model is created.
public abstract class BaseViewModel
{
protected BaseViewModel()
{
// apply any DefaultValueAttribute settings to their properties
var propertyInfos = this.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var attributes = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true);
if (attributes.Any())
{
var attribute = (DefaultValueAttribute) attributes[0];
propertyInfo.SetValue(this, attribute.Value, null);
}
}
}
}
And inherit from this in your ViewModels:
public class SearchModel : BaseViewModel
{
[DefaultValue(true)]
public bool IsMale { get; set; }
[DefaultValue(true)]
public bool IsFemale { get; set; }
}