Domanda

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.

È stato utile?

Soluzione

The DisplayFormat only applies to EditorFor or DisplayFor. Use

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

Altri suggerimenti

You could do this by using partial classes like below.

  1. Linq to SQL generates object classes are partial

  2. Create your own partial class for the objects

  3. Place the [MetadataType(typeof(YourDataAnnotationIncludedClassName))] on the partial class you created.

Sample Code:

Linq to SQL Generated Class

public partial class Provider 
{
   public string Name { get; set; }
}

Create your own MetaData class with Metadata for each field you want to validate

public class MyMetaDataProviderClass
{
    [Required]
    [DisplayName("Provider Name")]
    public string Name { get; set; }
}

Create another Partial Class for the Object class you want to add metadata to, here it's Provider class:

[MetadataType(typeof(MyMetaDataProviderClass))]
public partial class Provider { }

Important Note: you don't need to specify anything in the class, just the metadata type.

Then you can use this on your View likes below:

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

EDIT

For your decimal issue could be handled like below.

@Html.TextBox(m => Math.Round(m.Amount,2))

OR

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

For your date issue :

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

Additional Note:

DisplayFormat works only with EditorFor and DisplayFor helpers

I hope this will help to you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top