【问题标题】:TextBoxFor extesion with formatted value shows 0具有格式化值的 TextBoxFor 扩展显示 0
【发布时间】:2012-06-21 06:47:57
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    如果你想指定格式,你应该使用 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);
    }
    

    【讨论】:

    • 我在HtmlHelper 中看不到TextBox
    • 我想你的意思是System.Web.Mvc.Html.InputExtensions.TextBox(htmlHelper, fullHtmlFieldName, value, htmlAttributes);
    • 是的,它奏效了。我可以知道为什么TextBoxFor 接受 htmlAttributes 但不使用其value 属性吗?
    • @bjan,您在HtmlHelper 中看不到TextBox,因为您没有通过将using System.Web.Mvc.Html 添加到文件中来将扩展方法纳入范围。不,我根本不是指System.Web.Mvc.Html.InputExtensions.TextBox(htmlHelper, fullHtmlFieldName, value, htmlAttributes);。我故意改变了这一点。至于为什么 TextBoxFor 助手不允许更改 value 属性,那是设计使然 => 它使用作为第一个参数传递的 lambda 表达式中指定的模型属性的值。
    • 是的,它们完全一样。只是调用扩展方法的正确方法是在它扩展的类的实例上执行此操作,而不是直接调用静态方法。
    猜你喜欢
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-01-15
    • 2014-08-02
    • 1970-01-01
    • 2015-10-23
    • 2010-09-24
    相关资源
    最近更新 更多