mvc3 default values

2019-08-29 12:29发布

问题:

How can i define the default value for a model property? The attribute DefaultValue is not working:

    [DisplayName("Infos")]
    [DefaultValue("Test")]
    [DataType(DataType.MultilineText)]
    public object infos { get; set; }

回答1:

DefaultValue is not used for what you think it is.

From the DefaultValueAttribute MSDN page

You can create a DefaultValueAttribute with any value. A member's default value is typically its initial value. A visual designer can use the default value to reset the member's value. Code generators can use the default values also to determine whether code should be generated for the member.

Note: A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

Why not just set the defaults in a constructor for your Model?

public class MyModel {
    public MyModel() { infos = "Test"; }

    [DisplayName("Infos")]
    [DataType(DataType.MultilineText)]
    public ojbect infos { get; set; }
}

EDIT:

Since you seem to be using EF models and you want to set a default value. You just create a partial class with a constructor.

public partial class MyEntity {
    public MyEntity() { infos = "Test"; }
}