【问题标题】:Can not type a double in a textbox无法在文本框中键入双精度
【发布时间】:2012-08-28 10:12:31
【问题描述】:

我正在开发一个 mvc .net Web 应用程序,并且我正在使用实体框架来生成模型。我有包含双精度属性的类。我的问题是,当我使用@HTML.EditorFor(model => model.Double_attribute) 并测试我的应用程序时,我无法在该编辑器中输入双精度,我只能输入整数。 (我正在使用 Razor 引擎获取视图)如何解决这个问题?谢谢。

更新:我发现我可以键入具有这种格式的双精度 #,###(逗号后的 3 个数字,但我不想让用户键入特定格式,我想接受所有格式(1 个或更多逗号后面的数字) 有谁知道如何解决这个问题?问候

【问题讨论】:

  • 是否启用了客户端验证?您是否尝试使用不同的小数分隔符:.和 ,(点和逗号)?
  • 这是不正常的,你可能有一些 JS 脚本会产生问题。去掉js引用试试看。
  • 是的,它已被激活。我尝试了他们两个,但它没有工作
  • @HediNaily,你能发布你的模型定义吗?
  • 应该没什么区别,但你试过了吗,@HTML.EditorFor(model => model.Double_attribute)?另外,贴出你的型号代码,Model.Double_attribute有什么属性吗?

标签: asp.net asp.net-mvc asp.net-mvc-3 entity-framework


【解决方案1】:

您可以使用添加符号:

[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Double_attribute{ get; set; }

现在...瞧:您可以在视图中使用双精度:

@Html.EditorFor(x => x.Double_attribute)

对于其他格式,您可以检查this 或只是谷歌“DataFormatString double”您想要的该字段选项。

【讨论】:

  • 我只能键入具有这种格式的双精度 #,###(逗号后的 3 个数字,但我不想让用户键入特定格式,我想接受所有格式(1 或逗号后有更多数字)
【解决方案2】:

尝试使用自定义数据绑定器:

public class DoubleModelBinder : IModelBinder
{
    public object BindModel( ControllerContext controllerContext,
        ModelBindingContext bindingContext )
    {
        var valueResult = bindingContext.ValueProvider.GetValue( bindingContext.ModelName );
        var modelState = new ModelState { Value = valueResult };
        object actualValue = null;

        try
        {
            actualValue = Convert.ToDouble( valueResult.AttemptedValue,
                CultureInfo.InvariantCulture );
        }
        catch ( FormatException e )
        {
            modelState.Errors.Add( e );
        }

        bindingContext.ModelState.Add( bindingContext.ModelName, modelState );
        return actualValue;
    }
}

并在 global.asax 中注册 binder:

protected void Application_Start ()
{
    ...
    ModelBinders.Binders.Add( typeof( double ), new DoubleModelBinder() );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多