5

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

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

4

2 回答 2

2

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.

于 2012-09-07T11:01:52.693 回答
0

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:

protected void Application_Start ()
{
    ...
    ModelBinders.Binders.Add( typeof( double ), new DoubleModelBinder() );
}
于 2012-09-04T05:43:35.047 回答