Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html helpers for 'decimal' type and formatting?

property:

public decimal Cost { get; set; }

html helper:

<%: Html.TextBoxFor(m => m.Cost)%>

Question: when I am setting the Cost property, how do I format it? for example show a precision of two decimal points?

like image 778
VoodooChild Avatar asked Jan 06 '11 16:01

VoodooChild


3 Answers

I've tweaked Jamiec's answer above a little to (a) make it compile and (b) use the same underlying methods as the framework does:

public static MvcHtmlString DecimalBoxFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, decimal?>> expression, string format, object htmlAttributes = null)
{
    var name = ExpressionHelper.GetExpressionText(expression);

    decimal? dec = expression.Compile().Invoke(html.ViewData.Model);

    // Here you can format value as you wish
    var value = dec.HasValue ? (!string.IsNullOrEmpty(format) ? dec.Value.ToString(format) : dec.Value.ToString())
                : "";

    return html.TextBox(name, value, htmlAttributes);
}
like image 169
Gaz Avatar answered Oct 20 '22 00:10

Gaz


I recommend DisplayFor/EditorFor template helper.

// model class
public class CostModel {
  [DisplayFormat(DataFormatString = "{0:0.00}")]
  public decimal Cost {get;set;}
}

// action method
public ActionResult Cost(){
  return View(new CostModel{ Cost=12.3456})
}

// Cost view cshtml
@model CostModel

<div>@Html.DisplayFor(m=>m.Cost)</div>
<div>@Html.EditorFor(m=>m.Cost)</div>

// rendering html
<div>12.34</div>
<div><input class="text-box single-line" id="Cost" name="Cost" type="text" value="12.34" /></div>

Hope this help.

like image 44
takepara Avatar answered Oct 20 '22 01:10

takepara


You could define your own extension method, something like:

public static MvcHtmlString DecimalBoxFor<TEntity>(
            this HtmlHelper helper,
            TEntity model,
            Expression<Func<TEntity, Decimal?>> property,
            string formatString)
        {
            decimal? dec = property.Compile().Invoke(model);

            // Here you can format value as you wish
            var value = !string.IsNullOrEmpty(formatString) ? 
                              dec.Value.ToString(formatString) 
                            : dec.Value.ToString();
            var name = ExpressionParseHelper.GetPropertyPath(property);

            return helper.TextBox(name, value);
        }

And then usage would be:

<%Html.DecimalBoxFor(Model,m => m.Cost,"0.00")%>
like image 39
Jamiec Avatar answered Oct 19 '22 23:10

Jamiec