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

时间:2011-10-03 15:20:51

标签: asp.net-mvc asp.net-mvc-3

我有这个型号:

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

但根据我的研究和答案,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>
}

7 个答案:

答案 0 :(得分:118)

在构造函数中设置:

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

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

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

[HttpGet]
public ActionResult Search()
{
    return new View(new SearchModel());
}

答案 1 :(得分: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);
            }
        }
    }
}

并在ViewModels中继承:

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

答案 2 :(得分:10)

使用特定值:

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

答案 3 :(得分:1)

如果您需要将相同的模型发布到服务器,构造函数中具有默认bool值的解决方案将不适合您。让我们假设您有以下模型:

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

    public SearchModel()
    { 
        IsMale = true;
    }
}

在视图中你会有这样的东西:

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

问题是当用户取消选中此复选框并将其发布到服务器时 - 您最终会在构造函数中设置默认值(在本例中为true)。

所以在这种情况下,我最终只会在视图上指定默认值:

@Html.CheckBoxFor(n => n.IsMale, new { @checked = "checked" })

答案 4 :(得分:1)

<div class="form-group">
                    <label asp-for="Password"></label>
                    <input asp-for="Password"  value="Pass@123" readonly class="form-control" />
                    <span asp-validation-for="Password" class="text-danger"></span>
                </div>

使用:value =“ Pass @ 123”作为.net核心输入中的默认值

答案 5 :(得分:0)

你会有什么?您可能最终会得到默认搜索和从某处加载的搜索。默认搜索需要一个默认的构造函数,因此请使用Dismissile之类的构造函数。

如果你从其他地方加载搜索条件,那么你应该有一些映射逻辑。

答案 6 :(得分:0)

只是想对@ Dismissile的答案发表评论,因为我无法编辑他的答案,也没有添加评论,指出View构造函数调用new会导致错误(在Visual Studio 2015上测试过) ),这是有道理的,因为我们只是产生一个模型的实例,而不是View类。正确的代码行是:

return View(new SearchModel());