【发布时间】:2014-08-20 07:16:22
【问题描述】:
我正在尝试在 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; }
}
阅读后我看到[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>
所以当我现在提供一个创建表单时,我希望这些默认值出现在表单中。
我是否必须在控制器中初始化模型对象,设置默认值,然后将其传递给创建视图,就像它是一个编辑视图一样?
如果是这样,我如何创建一个构造函数来初始化部分类中的所有默认值?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-5 default-value