Asp.net-Mvc

雙值綁定問題

  • June 28, 2019

在我的項目中,我希望允許使用者以 2 種格式輸入雙精度值:使用“,”或“。” 作為分隔符(我對指數形式不感興趣)。預設值帶有分隔符 ‘.’ 不工作。我希望這種行為適用於復雜模型對像中的所有雙重屬性(目前我使用包含標識符和值的對象集合)。

我應該使用什麼:價值提供者或模型綁定器?請顯示解決我的問題的程式碼範例。

您可以使用自定義模型綁定器:

public class DoubleModelBinder : DefaultModelBinder
{
   public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
       var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
       if (result != null && !string.IsNullOrEmpty(result.AttemptedValue))
       {
           if (bindingContext.ModelType == typeof(double))
           {
               double temp;
               var attempted = result.AttemptedValue.Replace(",", ".");
               if (double.TryParse(
                   attempted,
                   NumberStyles.Number,
                   CultureInfo.InvariantCulture,
                   out temp)
               )
               {
                   return temp;
               }
           }
       }
       return base.BindModel(controllerContext, bindingContext);
   }
}

可以在以下位置註冊Application_Start

ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());

引用自:https://stackoverflow.com/questions/6520005