2012-06-21 48 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