我有这个型号:
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) 我试图在ASP.net MVC Web应用程序中设置字段的默认值.
我首先使用数据库,所以我为元数据添加了一个部分类,如下所示:
[MetadataType(typeof(RadioRoutingMetadata))]
public partial class RadioRouting
{
}
public partial class RadioRoutingMetadata
{
[DefaultValue("%")]
public string Slot { get; set; }
[Required(ErrorMessage = "This field is requied")]
[DefaultValue(0)]
public int BlockStart { get; set; }
[Required(ErrorMessage = "This field is requied")]
[DefaultValue(499)]
public int BlockEnd { get; set; }
[DefaultValue(-1)]
public int FallBackBaseIdentifier { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
读完后没有看到我[DefaultValue(T)]
在创建时没有将字段初始化为该值.但是Html帮助器方法不看这个字段吗?
这是我的看法:
<p>
@Html.LabelFor(model => model.Slot, htmlAttributes: new { @class = "control-label col-md-2" })
<span class="field">
@Html.EditorFor(model …
Run Code Online (Sandbox Code Playgroud)