Reputation: 11725
I have to display my decimal as 00.00. I have the following EditorTemplate
@model Decimal?
@if (Model.HasValue)
{
@Model.Value.ToString("00.00");
}
I have to display the decimal in a textbox and label as well. How can I use the above Template to display the following in the wanted format.
@Html.TextBoxFor(m=>@item.Price)
@Html.LabelFor(m=>@item.Price)
Upvotes: 1
Views: 1381
Reputation: 1038710
You could use the [DisplayFormat]
attribute on your model:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:00.00}", NullDisplayText = "")]
public decimal? Price { get; set; }
and then to display:
@Html.DisplayFor(x => x.Price)
and to edit:
@Html.EditorFor(x => x.Price)
Upvotes: 3
Reputation: 24522
In your template you can use
@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("00.00") : String.Empty))
or
@if (Model.HasValue) {
@Model.Value.ToString("00.00");
@Html.TextBox("", Model.Value.ToString("00.00"))
}
Then in your view use
@Html.EditorFor(m => m.Price)%>
Upvotes: 0
Reputation: 6019
create a Decimal.ascx under Views\Shared\EditorTemplates folder
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<decimal?>" %>
<%
Html.LabelFor(m => m);
Html.TextBox (ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty),
Model.HasValue ? Model.Value.ToString("00.00") : "00.00", new {readonly = "readonly"}) %>
if all you need is displaying it, in that case switch Editor for Display (DisplayTemplates, DisplayFor, etc) readonly attribute is to make the textbox read-only (un-editable)
Upvotes: 0