Default value in an asp.net mvc view model

后端 未结 6 567
星月不相逢
星月不相逢 2020-12-05 01:37

I have this model:

public class SearchModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale         


        
6条回答
  •  长情又很酷
    2020-12-05 01:51

    Create a base class for your ViewModels with the following constructor code which will apply the DefaultValueAttributeswhen 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; }
    }
    

提交回复
热议问题