Mvc3 defaults

How do I define a default value for a model property? Attribute DefaultValue

doesn't work:

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

      

0


source to share


1 answer


DefaultValue is not used for what you think.

From the DefaultValueAttribute MSDN page

You can create the DefaultValueAttribute with any value. The default value for a member is usually its initial value. The visual designer can use the default to reset the member value. Code generators can also use default values ​​to determine if code should be generated for a member.

Note: The DefaultValueAttribute will not cause the member to be automatically initialized to the value of the attribute. You must set the initial value in your code.

Why not just set default values ​​in the 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 the default. You are just creating a partial class with a constructor.

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

      

+7


source







All Articles