問題を再現できなかったため、この問題は MVC4 で解決されたようです。空のテキスト ボックスはすべてnull
、モデルの null 許容の int、double、または decimal にバインドされます。問題ない。したがって、問題は別の場所にある可能性があります。または、これが MVC3 のバグであった可能性があります。
とはいえ、それでも問題が発生し、MVC4 を使用できない場合は、独自のカスタム モデル バインダーを作成して、必要なことを正確に実行してみてください。10 進数の例を次に示します。
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());