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.
In practice, you could create the ViewModel, and override these defaults with values pulled from a database entry (using the data-backed model), but as-is, this will always use these default values.
Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.
The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created. For example, if you set the DefaultValue property for a text box control to =Now(), the control displays the current date and time.
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.
class Person { public Person() { Age = 18; } public int Age { get; set; } }
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
class Person {
public Person() {
Age = 18;
}
public int Age { get; set; }
}
Controller
public ActionResult Create() {
return View(new Person());
}
It works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With