Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Annotating properties on a model with default values

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...