Annotating properties on a model with default values

后端 未结 5 1975
说谎
说谎 2020-12-01 05:40

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:



        
相关标签:
5条回答
  • 2020-12-01 05:57

    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.

    0 讨论(0)
  • 2020-12-01 05:58

    Assuming that your view has a definition such as:-

    @model Person
    

    and your controllers HTML GET returns an empty View

    return View();
    

    Then simply add a class that can be rendered that contains default values

    return View(new Person{ Age = 18 });
    

    Another option is to add a singleton static helper to your Person class that returns a default, populated class

      static public Person GetDefaultNew()
            {
                return new Person{ Age = 18 };
            }
    

    Then you need

    return View(new Person.GetDefaultNew());
    
    0 讨论(0)
  • 2020-12-01 06:00
    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.

    0 讨论(0)
  • 2020-12-01 06:07

    Setting JSON.net's DefaultValueHandling parameter makes DefaultValue work:

    class Person {
        [JsonProperty("Age", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
        [DefaultValue(18)]
        public int Age { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-01 06:17

    Model

    class Person {
        public Person() {
            Age = 18;    
        }
        public int Age { get; set; }
    }
    

    Controller

    public ActionResult Create() {
        return View(new Person());
    }
    

    It works fine.

    0 讨论(0)
提交回复
热议问题