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?
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);
}
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.
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")%>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With