2012-06-21 50 views
0

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

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无论任何价值。 我在哪里错了,或者我能做些什么来修复它?

回答

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); 
} 
+0

我不能看到'TextBox'在'HtmlHelper' – bjan

+0

我想你的意思'System.Web.Mvc.Html.InputExtensions。 TextBox(htmlHelper,fullHtmlFieldName,value,htmlAttributes);' – bjan

+0

是的,它的工作。我可以知道为什么'TextBoxFor'接受htmlAttributes但不使用它的'value'属性? – bjan