在MVC Web应用程序中设置默认值

Zap*_*ica 3 asp.net-mvc default-value asp.net-mvc-5

我试图在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 => 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>
Run Code Online (Sandbox Code Playgroud)

所以,当我现在提供一个创建表单时,我希望这些默认值在表单中.

我是否必须在控制器中初始化Model对象,设置默认值,然后将其传递给create视图,就像它是编辑视图一样?

如果是这样,我如何创建一个初始化分部类中所有默认值的构造函数?

Kar*_*sla 8

DefaultValue attribute不使用像你想要的属性来设置默认值.实际上,它根本不是由运行时直接使用的.它的目的是供Visual Studio设计人员使用.

更多信息:

http://support.microsoft.com/kb/311339

要么

属性上的.Net DefaultValueAttribute


您可以在MVC中轻松设置字段的默认值:

 @Html.EditorFor(model => model.BlockEnd, new { htmlAttributes = new { @class = "form-control", @Value = "499" } })
Run Code Online (Sandbox Code Playgroud)

现在与上面的代码第一次时表格将加载初始值BlockEnd将是499