Product Price返回的fasle为Modelstate Valid



我有一个类似

class Product{
  public string ProductName {get;set;}
  public decimal ProductPrice {get;set;}
}

视图中,我引用顶部的模型

并使用CCD_ 1创建输入

 @Html.TextBoxFor(n => n.Transaction.ProductName )
 @Html.TextBoxFor(n => n.Transaction.ProductPrice )

所有这些都有效,现在当我将1.11输入到产品价格中时,它可以很好地进行

但如果我输入类似240,000的内容,ModelState is not valid

为什么?正确的方法是什么?如何创建一个只处理价格的文本框?没有文本输入?

尝试为十进制数据类型实现一个自定义模型绑定器,该绑定器将根据您当前的区域性来解析十进制值:

public class PriceModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = value };
        decimal result = 0.0M;
        if (!decimal.TryParse(value.AttemptedValue, NumberStyles.Currency, CultureInfo.CurrentCulture, out result))
            modelState.Errors.Add(new FormatException("Price is not valid"));
        return result;
    }
}

尝试将您的,(逗号)更改为。(点)

在c#中使用。(点)表示十进制值(不是类型,实际十进制值)
相反,使用字符串格式将您的值从2016000.5转换为2 016 000,5或2016000.5(如果这是您要查找的)

您的问题可能是"240000"中的逗号。你有两个选择:

(a) 将文本框限制为仅数字字符

@Html.TextBoxFor(n => n.TransactionProductPrice, new { type = "number" })

(b) 将ProductPrice的类型更改为字符串,然后在控制器端用逗号将数千分隔为十进制来解析字符串(请参阅其他问题以获得帮助)

var allowedStyles = (NumberStyles.AllowDecimalPoint & NumberStyles.AllowThousands);
var price = Decimal.Parse(viewmodel.TransactionProductPrice, allowedStyles);

相关内容

最新更新