asp.net-mvc-3modelmetadata

Apply model metadata on complex objects


I have the following scenario

public class Foo {
    public Bar FooBar { get; set; }
}

public class Bar {
    [DisplayFormatAttribute(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public DateTime BirthDay { get; set; }
}

Now when I use EditorFor I want to apply the DataFormatString on my DateTime

@Html.EditorFor(x => x.FooBar.BirthDay);

The above code does not render the date correct using the DisplayFormatAttribute, so how can I solve this?


Solution

  • you might have to use this i think.

    public class Bar {
        [DataType(DataType.Date), DisplayFormat( DataFormatString="{0:dd/MM/yy}", ApplyFormatInEditMode=true )]
        public DateTime BirthDay { get; set; }
    }
    

    OR you can use like this

    [DisplayFormat(DataFormatString = "{0:d}")]
    [DataType(DataType.Date)]
    public DateTime BirthDay { get; set; }
    

    in your view, you can try this.

    @Html.EditorFor(x => x.FoorBar.BirthDay.ToString("dd/MM/yyyy"))