使用默认值注释模型上的属性 [英] Annotating properties on a model with default values

查看:28
本文介绍了使用默认值注释模型上的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 EF4.1 代码优先模型(可能重要也可能不重要),并且我正在尝试为我的 Create scaffold 模板获取默认值.我的模型看起来像:

class Person {[默认值 (18)]公共整数年龄{得到;放;}}

然后我的创建视图看起来像:

@Html.LabelFor(model =>model.Age)

<div class="editor-field">@Html.EditorFor(model => model.Age)@Html.ValidationMessageFor(model =>model.Age)

我希望在运行时,EditorFor 会用18"预先填充文本框,但它没有这样的事情.我是不是误解了 DefaultValue 属性的用途,还是我应该做的其他事情?

注意:我不想在 EditorFor 方法上使用 new { Value = "18" } 覆盖,它似乎破坏了 DRY.

解决方案

我不知道这是否能满足您的 DRY 需求,但我认为这是一个开始.

我会像这样重新设计模型:

public class Person {私有常量 int DEFAULT_AGE = 18;私人 int _age = DEFAULT_AGE;[默认值(DEFAULT_AGE)]公共整数年龄{得到{返回_年龄;}设置 { _age = 值;}}}

保持视图不变,但在创建操作中执行以下操作:

public ActionResult Create() {返回视图(新人());}

这样,输入文本框将使用默认的 Age 值创建,并且只有一个地方会指定该默认值.

I created an EF4.1 code-first model (may or may not be important), and I'm trying to get default values for my Create scaffold template. My model looks like:

class Person {
    [DefaultValue (18)]
    public int Age { get; set; }
}

And then my Create view looks like:

<div class="editor-label">
    @Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Age)
    @Html.ValidationMessageFor(model => model.Age)
</div>

I would expect at runtime, that the EditorFor would pre-populate the textbox with "18", but it does no such thing. Am I misunderstanding what the DefaultValue attribute is for, or is there something else I should be doing?

Note: I don't want to use the new { Value = "18" } override on the EditorFor method, it seems to break DRY.

解决方案

I don't know if this will satisfy your DRY needs, but it's a start I think.

I would rework the model a bit like this:

public class Person {
    private const int DEFAULT_AGE = 18;
    private int _age = DEFAULT_AGE;
    [DefaultValue(DEFAULT_AGE)]
    public int Age {
        get { return _age; }
        set { _age = value; }
    }
}

Keep the view as is, but in the create action do this:

public ActionResult Create() {
    return View(new Person());
}

That way, the input textbox will be created with the default Age value, and there will be only one place where that default will be specified.

这篇关于使用默认值注释模型上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆