7

私のプロジェクトでは、ユーザーが2つの形式で2つの値を入力できるようにしたいとします。 '、'または '。'を使用します。区切り記号として(私は指数関数形式に興味がない)。デフォルトでは、区切り文字 '。'動作しません。 この動作は、複雑なモデルオブジェクトのすべてのdoubleプロパティで機能します(現在、私は識別子と値を含むオブジェクトのコレクションを扱います)。二重値バインドの問題

私は何を使用する必要がありますか:値プロバイダーまたはモデルバインダー?私の問題を解決するためのコード例を示してください。

+2

http://stackoverflow.com/questions/5050641/asp-net-mvc-をモデルバインダーとグローバル番号形式はまったく同じですか? – iwayneo

答えて

17

カスタムモデルバインダー使用することができます

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()); 
+0

明確な答えをありがとうございますが、バリュープロバイダーの目的は何ですか?それはフォームの値のコレクション、URLパラメータ、サーバー変数、クッキーなどのようなさまざまなソースの抽象化ですか? –

+0

さらに、Nullable型に同じバインダを追加することを忘れないでください – vasilyk

関連する問題