具有格式化值的TextBoxFor扩展显示0

时间:2012-06-21 06:47:58

标签: c# asp.net-mvc-3 razor html-helper

我无法使用EditorFor,因为我的输入还有其他一些属性,例如readonlydisableclass因此我使用了TextBoxFor的扩展名。我需要显示格式化的数值,所以我的扩展方法定义为

public static MvcHtmlString FieldForAmount<TModel, TValue>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TValue>> expression)
{
    MvcHtmlString html = default(MvcHtmlString);
    Dictionary<string, object> newHtmlAttrib = new Dictionary<string, object>();

    newHtmlAttrib.Add("readonly", "readonly");
    newHtmlAttrib.Add("class", "lockedField amountField");

    var _value = ModelMetadata.FromLambdaExpression(expression, 
                     htmlHelper.ViewData).Model;
    newHtmlAttrib.Add("value", string.Format(Formats.AmountFormat, value));

    html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, 
        expression, newHtmlAttrib);
    return html;
}

Formats.AmountFormat定义为"{0:#,##0.00##########}"

让我们说_value为2,newHtmlAttrib将其显示为2.00,但结果html显示为0,它始终显示为0任何价值。 我错在哪里或者我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:0)

如果要指定格式,则应使用TextBox帮助程序:

public static MvcHtmlString FieldForAmount<TModel, TValue>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TValue>> expression
)
{
    var htmlAttributes = new Dictionary<string, object>
    {
        { "readonly", "readonly" },
        { "class", "lockedField amountField" },
    };

    var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var value = string.Format(Formats.AmountFormat, metadata.Model);
    var name = ExpressionHelper.GetExpressionText(expression);
    var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

    return htmlHelper.TextBox(fullHtmlFieldName, value, htmlAttributes);
}