Annotating properties on a model with default values

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.

Leave a Comment