0

我不能使用 EditorFor,因为我的输入有一些其他属性,例如readonlydisable因此class我正在使用 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无论任何值。我在哪里错了,或者我能做些什么来修复它?

4

1 回答 1

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);
}
于 2012-06-21T06:56:19.420 回答