我试图在ASP.net MVC Web应用程序中设置字段的默认值. 我首先使用数据库,所以我为元数据添加了一个部分类,如下所示: [MetadataType(typeof(RadioRoutingMetadata))]public partial class RadioRouting{}public
我首先使用数据库,所以我为元数据添加了一个部分类,如下所示:
[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; } }
读完后没有看到[DefaultValue(T)]在创建时没有将字段初始化为该值.但是Html帮助器方法不看这个字段吗?
这是我的看法:
<p> @Html.LabelFor(model => model.Slot, htmlAttributes: new { @class = "control-label col-md-2" }) <span class="field"> @Html.EditorFor(model => model.Slot, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Slot, "", new { @class = "text-danger" }) </span> </p> <p> @Html.LabelFor(model => model.BlockStart, htmlAttributes: new { @class = "control-label col-md-2" }) <span class="field"> @Html.EditorFor(model => model.BlockStart, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BlockStart, "", new { @class = "text-danger" }) </span> </p> <p> @Html.LabelFor(model => model.BlockEnd, htmlAttributes: new { @class = "control-label col-md-2" }) <span class="field"> @Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.BlockEnd, "", new { @class = "text-danger" }) </span> </p>
所以,当我现在提供一个创建表单时,我希望这些默认值在表单中.
我是否必须在控制器中初始化Model对象,设置默认值,然后将其传递给create视图,就像它是编辑视图一样?
如果是这样,我如何创建一个初始化分部类中所有默认值的构造函数?
DefaultValue属性不用于根据需要在属性上设置默认值.实际上,它根本不是由运行时直接使用的.它的目的是供Visual Studio设计人员使用.更多信息:
http://support.microsoft.com/kb/311339
要么
.Net DefaultValueAttribute on Properties
您可以在MVC中轻松设置字段的默认值:
@Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control", @Value = "499" } })
现在用上面的代码第一次表单将加载BlockEnd的初始值将是499