Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
377 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...