我有这个模型:
public class SearchModel
{
[DefaultValue(true)]
public bool IsMale { get; set; }
[DefaultValue(true)]
public bool IsFemale { get; set; }
}
但根据我的研究和答案,DefaultValueAttribute
实际上并未设置默认值。但这些答案来自 2008 年,是否有比使用私有(private)字段在传递到 View 时将这些值设置为 true 的属性或更好的方法?
无论如何,这都是 View :
@using (Html.BeginForm("Search", "Users", FormMethod.Get))
{
<div>
@Html.LabelFor(m => Model.IsMale)
@Html.CheckBoxFor(m => Model.IsMale)
<input type="submit" value="search"/>
</div>
}
最佳答案
在构造函数中设置:
public class SearchModel
{
public bool IsMale { get; set; }
public bool IsFemale { get; set; }
public SearchModel()
{
IsMale = true;
IsFemale = true;
}
}
然后将其传递到 GET 操作中的 View :
[HttpGet]
public ActionResult Search()
{
return new View(new SearchModel());
}
关于asp.net-mvc - asp.net mvc View 模型中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7637022/