Search code examples
asp.net-coremodel-view-controllerrazormodel

How to set DisplayFormat on a Model property


I have set the [DisplayFormat(DataFormatString = "{0:C}")] on my field Deductible but it still not applying the display format. Can anyone help. TY

enter image description here

CSHTML.CS

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public DateTime HireDate { get; set; }
    //public List<Phone> PhoneNumbers { get; set; }
    //public
    //Address Address { get; set; }

    [DisplayFormat(DataFormatString = "{0:C}")]
    public decimal Deductible { get; set; }

CSHTML:

@for (var i = 0; i < Model.Contacts.Count; i++)
            <div class="col-sm">
                <label asp-for="@Model.Contacts[i].Deductible" class="control-label"> </label>
                <input asp-for="@Model.Contacts[i].Deductible class=" control-label" value="@Model.Contacts[i].Deductible">
            </div>

Solution

  • [DisplayFormat] is respected when you use DisplayFor() and EditorFor

    Try:

     @Html.DisplayFor(model => model.Contacts[i].Deductible)
    

    OR

    <input asp-for="@Model.Contacts[i].Deductible class=" control-label" value="@Model.Contacts[i].Deductible.ToString("C2")">
    

    Result:

    enter image description here

    Or

    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)]
    

    and use

    @Html.EditorFor(model => model.Contacts[i].Deductible)
    

    Update If you use

    [DisplayFormat(DataFormatString = "{0:C}")]
    

    and

    @Html.EditorFor(model => model.Contacts[i].Deductible)
    

    In the post you will get: enter image description here