0

価格プロパティを持つこのビューモデルクラスがあります。

問題は、ユーザーが入力した値$200,150.90がフォーマットされておらず、コントローラーに送信された場合です。

10 進数のデフォルト モデル フォーマッタの問題は何ですか?

public ItemViewModel
{

public string Name {get;set;}
[DisplayFormat(DataFormatString = "{0:c}")]
[RegularExpression(@"^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$"
ErrorMessage = "Enter a valid money value. 2 Decimals only allowed")]
public decimal? Price{ get; set; }
}

ビューで

@model ItemViewModel

@Html.TextBoxFor(m=>m.Price)

コントローラー内

public ActionResult Save(ItemViewModel model)
{

 // model.Price is always null, even if it has value $200,150.90
}

この 10 進モデル バインダーを登録しましたGlobal.asax

   ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

   public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }

モデル バインダーのエラーInput string was not in a correct format

 Convert.ToDecimal("$200,150.90",CultureInfo.CurrentCulture)
4

1 に答える 1