使用默认值注释模型上的属性
我创建了一个 EF4.1 代码优先模型(可能重要也可能不重要),并且我正在尝试获取“创建脚手架”模板的默认值。我的模型看起来像:
class Person {
[DefaultValue (18)]
public int Age { get; set; }
}
然后我的创建视图看起来像:
<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 会用“18”预先填充文本框,但它没有这样做。我是否误解了 DefaultValue 属性的用途,或者我还应该做其他事情?
注意:我不想在 EditorFor 方法上使用 new { Value = "18" }
重写,它似乎破坏了 DRY。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不知道这是否能满足您的 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:
Keep the view as is, but in the create action do this:
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.
在这种情况下,每次创建新的 Person 时,年龄都会被初始化为 18,即使新对象是由 Model Binder 创建的。
In this scenario, every time you do a new Person age will be initialized with 18 as age, even when the new object is created by the Model Binder.
模型
控制器
工作正常。
Model
Controller
It works fine.
假设您的视图具有如下定义: -
并且您的控制器 HTML GET 返回一个空视图
然后只需添加一个可以呈现的包含默认值的类
另一种选择是向您的 Person 类添加一个返回默认值的单例静态帮助器,填充类
那么你需要
Assuming that your view has a definition such as:-
and your controllers HTML GET returns an empty View
Then simply add a class that can be rendered that contains default values
Another option is to add a singleton static helper to your Person class that returns a default, populated class
Then you need
设置 JSON.net 的 DefaultValueHandling 参数使 DefaultValue 起作用:
Setting JSON.net's DefaultValueHandling parameter makes DefaultValue work: