この問題は、問題を再現できないため、MVC4で解決されたようです。空のテキストボックスはすべて、null
を私のモデルのnull、int、double、またはdecimalにバインドします。問題ありません。だから問題はどこか他の場所にあるかもしれませんが、これはMVC3のバグだった可能性があり、もはやそれはありません。
しかし、まだ問題が発生していてMVC4を使用できない場合は、独自のカスタムモデルバインダーを作成してください。ここでは、小数点のための一例です:
public class NullableDecimalBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object result = null;
if (valueResult.AttemptedValue.Length > 0) {
try {
// Bonus points: This will bind using the user's current culture.
result = Convert.ToDecimal(valueResult.AttemptedValue, System.Globalization.CultureInfo.CurrentCulture);
} catch (FormatException e) {
modelState.Errors.Add(e);
} catch (InvalidOperationException e) {
modelState.Errors.Add(e);
}
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return result;
}
}
次に、それを使用するために、あなたのGlobal.asaxのApplication_Start
に次の行を追加します
ModelBinders.Binders.Add(typeof(decimal?), new NullableDecimalBinder());
ジャストオフのチャンスに:あなたは、あなたのモデルをインスタンス化するとき、前にそれにバインドすると、nullable doubleとdecimalsはその時点でどのような値を持っていますか? –
コードを投稿することができれば助かります。 –