[英]Can not type a double in a textbox
我正在開發一個mvc .net web應用程序,我正在使用Entity Framework來生成Model。 我有包含雙精度屬性的類。 我的問題是,當我使用@HTML.EditorFor(model => model.Double_attribute)
並測試我的應用程序時,我無法在該編輯器中輸入double,我只能輸入整數。 (我正在使用Razor引擎查看)如何解決這個問題? 謝謝。
更新:我發現我可以鍵入一個具有這種格式的雙#,###(逗號后面有3個數字,但我不想讓用戶輸入特定格式,我想接受所有格式(后面有1個或更多個數字)逗號)有沒有人知道如何解決這個問題?問候
您可以使用添加表示法:
[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Double_attribute{ get; set; }
現在......瞧:您可以在視圖中使用雙精度圖:
@Html.EditorFor(x => x.Double_attribute)
對於其他格式,您可以檢查此格式或只是谷歌“DataFormatString double”您對此字段的所需選項。
嘗試使用自定義數據倉:
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() );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.