简体   繁体   English

无法在文本框中键入double

[英]Can not type a double in a textbox

I'm working on an mvc .net web application and I'm using Entity Framework for generating Model. 我正在开发一个mvc .net web应用程序,我正在使用Entity Framework来生成Model。 I have classes that contain attributes that are doubles. 我有包含双精度属性的类。 My problem is that when I use @HTML.EditorFor(model => model.Double_attribute) and test my application I can't type a double in that editor, I only can type integers. 我的问题是,当我使用@HTML.EditorFor(model => model.Double_attribute)并测试我的应用程序时,我无法在该编辑器中输入double,我只能输入整数。 (I'm using Razor engine for views)How to solve this? (我正在使用Razor引擎查看)如何解决这个问题? Thanks. 谢谢。

Update : I discovered that I can type a double having this format #,### (3 numbers after the comma but I do not want to make user type a specific format, I want to accept all formats (1 or more numbers after the comma) Does anyone have an idea how to solve this? Regards 更新:我发现我可以键入一个具有这种格式的双#,###(逗号后面有3个数字,但我不想让用户输入特定格式,我想接受所有格式(后面有1个或更多个数字)逗号)有没有人知道如何解决这个问题?问候

You could use add notations : 您可以使用添加表示法:

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

And now... voila : you can use the double in your view : 现在......瞧:您可以在视图中使用双精度图:

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

For other formats you could check this or just google "DataFormatString double" your desired option for this field. 对于其他格式,您可以检查格式或只是谷歌“DataFormatString double”您对此字段的所需选项。

try to use custom databinder: 尝试使用自定义数据仓:

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;
    }
}

and register binder in global.asax: 并在global.asax中注册binder:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM