加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在MVC Web应用程序中设置默认值

发布时间:2020-12-16 09:13:39 所属栏目:asp.Net 来源:网络整理
导读:我试图在ASP.net MVC Web应用程序中设置字段的默认值. 我首先使用数据库,所以我为元数据添加了一个部分类,如下所示: [MetadataType(typeof(RadioRoutingMetadata))]public partial class RadioRouting{}public partial class RadioRoutingMetadata{ [Defaul
我试图在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>

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

我是否必须在控制器中初始化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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读