How do I format decimal as Percentage in EF Code First rendered in Razor TextBoxFor?

asp.net-mvc c# entity-framework razor

Question

I have a property:

    public decimal myProperty { get; set; }

And here is my render:

    @Html.TextBoxFor(m => m.myProperty , new { @class = "percentage" })

How do I do the Percentage?

1
2
5/9/2013 3:44:16 PM

Accepted Answer

You could decorate your view model property with the [DisplayFormat] attribute allowing you to specify a format:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:P2}")]
public decimal myProperty { get; set; }

and in your view:

@Html.EditorFor(x => x.myProperty)

But be careful because the DisplayFormat attribute (as it name suggests) is used only for displaying purposes. It is not used by the default model binder. So when the user submits this value by posting the form chances are you will get a validation error because for example 0.45% is not a valid decimal value. I have illustrated in this post how a custom model binder could be defined which will use the format defined by the DisplayFormat attribute when binding back the value.

9
5/23/2017 12:34:22 PM

Popular Answer

Here is how I ended up using one of the suggestions in the post.

public class JobCand
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int JC_ID { get; set; }

    public int Job_ID { get; set; }

    public int Candidate_ID { get; set; }

    [DataType(DataType.MultilineText)]
    [StringLength(250)]
    public string JC_Note { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = false, DataFormatString = "{0:P0}")]
    [RegularExpression(@"[0-9]+(\.[0-9][0-9]?)?$", ErrorMessage = "Invalid rate")]
    public decimal? JC_Skill_Match_Pct { get; set; }

}

I will tell you one thing compared to ASP.NET controls and C#.NET code behind formatting this way is much easier. I like the way MVC suggests doing this all in the entity class. The application I built for the Assessor's office in Clark County required a lot of accounting displays with $ and % formatting. The work to convert back and forth for display, editing and extraction and updates to the database caused me a lot of pain. Not to mention that I had update panels in the mix.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow