在使用默认值的模型的属性注解 [英] Annotating properties on a model with default values
问题描述
我创建了一个EF4.1 code-第一种模式(可能并不重要),而我试图让默认值我创建脚手架模板。我的模型是这样的:
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>
我希望在运行时,该EditorFor将美元,18P $ P-填充文本框,但它确实没有这样的事。我误解了默认值属性是什么,或者有什么别的我应该做的事?
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?
请注意:我不想使用新{值=18}
覆盖上EditorFor方法,它似乎打破DRY
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屋!