5 asp.net asp.net-mvc entity-framework asp.net-mvc-3
我正在开发一个mvc .net web应用程序,我正在使用Entity Framework来生成Model.我有包含双精度属性的类.我的问题是,当我使用@HTML.EditorFor(model => model.Double_attribute)并测试我的应用程序时,我无法在该编辑器中键入double,我只能输入整数.(我正在使用Razor引擎查看)如何解决这个问题?谢谢.
更新:我发现我可以键入一个具有这种格式的双#,###(逗号后面有3个数字,但我不想让用户输入特定格式,我想接受所有格式(后面有1个或更多个数字)逗号)有没有人知道如何解决这个问题?问候
尝试使用自定义数据绑定器:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
并在global.asax中注册binder:
protected void Application_Start ()
{
...
ModelBinders.Binders.Add( typeof( double ), new DoubleModelBinder() );
}
Run Code Online (Sandbox Code Playgroud)