ASP.NET MVC视图模型中的默认值

Default value in an asp.net mvc view model

我有这个模型:

1
2
3
4
5
6
7
public class SearchModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}

但是根据我在这里的研究和回答,DefaultValueAttribute实际上没有设置默认值。 但是这些答案来自2008年。有没有一种属性或比传递给视图时使用私有字段将这些值设置为true更好的方法?

反正这是视图:

1
2
3
4
5
6
7
8
@using (Html.BeginForm("Search","Users", FormMethod.Get))
{

    @Html.LabelFor(m => Model.IsMale)
    @Html.CheckBoxFor(m => Model.IsMale)
    <input type="submit" value="search"/>

}

在构造函数中设置:

1
2
3
4
5
6
7
8
9
10
11
public class SearchModel
{
    public bool IsMale { get; set; }
    public bool IsFemale { get; set; }

    public SearchModel()
    {
        IsMale = true;
        IsFemale = true;
    }
}

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

1
2
3
4
5
[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}


MXU11

a>
使用特定值?/p>b>

1
2
[Display(Name ="Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6

使用以下构造函数代码为ViewModels创建基类,当创建任何继承模型时,它们将应用DefaultValueAttributes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
            }
        }
    }
}

并在您的ViewModels中继承自此:

1
2
3
4
5
6
7
public class SearchModel : BaseViewModel
{
    [DefaultValue(true)]
    public bool IsMale { get; set; }
    [DefaultValue(true)]
    public bool IsFemale { get; set; }
}


如果您需要将同一模型发布到服务器,则在构造函数中具有默认bool值的解决方案将不可行。假设您有以下模型:

1
2
3
4
5
6
7
8
9
public class SearchModel
{
    public bool IsMale { get; set; }

    public SearchModel()
    {
        IsMale = true;
    }
}

在视图上,您?吹揭韵履谌荩?/p>>

1
@Html.CheckBoxFor(n => n.IsMale)

>
问题是,当用户取消选中此复选框并将其发布到服务器时,最终将在构造函数中设置默认?ㄔ谡庵智榭鱿挛猼r))?/p>b>

a>
因此,在这种情况下,我最终将只在视图上指定默认值?/p>b>

[cc]@Html.CheckBoxFor(n => n.IsMale, new { @checked ="checked" })
[/c


你会有什么?您可能最终会得到默认搜索以及从某个位置加载的搜索。默认搜索需要一个默认的构造函数,因此建议使用Dismissile。

如果从其他位置加载搜索条件,则可能应该具有一些映射逻辑。