asp.net mvc视图模型中的默认值

Sha*_*ean 64 asp.net-mvc asp.net-mvc-3

我有这个型号:

public class SearchModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但根据我的研究和答案,DefaultValueAttribute实际上并没有设置默认值.但是这些答案来自2008年,是否有一个属性或更好的方法,而不是使用私有字段将这些值设置为true传递给视图?

无论如何,继承人的观点:

@using (Html.BeginForm("Search", "Users", FormMethod.Get))
{
<div>
    @Html.LabelFor(m => Model.IsMale)
    @Html.CheckBoxFor(m => Model.IsMale)
    <input type="submit" value="search"/>
</div>
}
Run Code Online (Sandbox Code Playgroud)

Dis*_*ile 120

在构造函数中设置:

public class SearchModel
{
    public bool IsMale { get; set; }
    public bool IsFemale { get; set; }

    public SearchModel()
    { 
        IsMale = true;
        IsFemale = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其传递给GET操作中的视图:

[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*rue 15

ViewModels使用以下构造函数代码为您创建基类,该代码将在DefaultValueAttributes创建任何继承模型时应用.

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在ViewModels中继承:

public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是一个聪明的解决方案,但我建议使用C#6,使用类似的自动属性初始化器更好(更高性能):`public bool IsMale {get; 组; } = true` (3认同)

Gur*_*ash 12

使用特定值:

[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6
Run Code Online (Sandbox Code Playgroud)