Search code examples
asp.net-mvcrazorasp.net-mvc-4data-annotationsrazor-2

Using DataAnnotations with a Linq generated class


I followed the steps I found online to do this, but it doesn't seem to be working. This is an MVC4 project using Razor2.

Here is my metadata class I created

public class LedgerItemValidation
{
    [DisplayFormat(DataFormatString = "{0:#,##0.00#}", ApplyFormatInEditMode = true)]
    public decimal Amount { get; set; }

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

And here is the partial class I created so I could apply these

[MetadataType(typeof(LedgerItemValidation))]
public partial class LedgerItem
{
    ... other stuff
}

And here is where I display it on the page

@model CF.Models.LedgerItem

@Html.TextBoxFor(m => m.Amount)

From what I could see online this should be all I have to do. As I test I gave it a DisplayName also but that didn't show up either.

Not sure what I'm missing here.


Solution

  • The DisplayFormat only applies to EditorFor or DisplayFor. Use

    @Html.EditorFor(m => m.Amount)