无法绑定Decimal属性以在MVC中查看

时间:2016-07-08 04:42:04

标签: c# asp.net-mvc

我的模特中有一个属性。当我提交表格时,我收到了以下错误。

无法转换类型' System.Decimal'的对象输入' System.Array'

我正在使用MVC 5

public class PaymentInformationModel
{
    [Display(Name = "Payment Amount")]
    [Required(ErrorMessage = "Please enter the {0}")]
    [MaxLength(9)]
    [RegularExpression(@"^\d+.\d{0,2}$")]
    [Range(0, 9999999999999999.99)]
    public decimal PaymentAmount { get; set; }
}

出了什么问题。我正在输入正常的数字,如123.34。

控制器

[HttpPost]
public ActionResult Index(PaymentInformationModel model)
{
    if (ModelState.IsValid)
    {
        return View();
    }
    return View();
}

查看

@model PaymentInformationModel

@using (Html.BeginForm("", "Payment", FormMethod.Post, new { Id = "Form1", @class = "form-horizontal" }))
{
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">Payment Information</div>
            <div class="panel-body">
                <div class="form-group">
                    @Html.LabelFor(x => x.PaymentAmount, new { @class = "control-label col-sm-2" })
                    <div class="input-group col-sm-3">
                        <span class="input-group-addon">$</span>
                        @Html.TextBoxFor(m => m.PaymentAmount, new { @class = "form-control col-sm-10" })
                    </div>
                    @Html.ValidationMessageFor(m => m.PaymentAmount, "", new { @class = "help-block" })
                </div>


            </div>
        </div>


    </div>
    <button type="submit" name="btnSubmit" id="btnSubmit" class="btn btn-success">PAY</button>
}

2 个答案:

答案 0 :(得分:4)

您正在使用MaxLength属性,该属性不适用于十进制数据类型。我不确定RegularExpression属性是否有效,但我没有验证。

尝试删除这两个属性,看看您的代码是否正常运行。如果确实如此 - 您可能需要考虑使用其他属性的方法,这些属性可以正确地使用十进制类型(并且Range验证器似乎是一个很好的候选者。)

只是看看MaxLength是否可以成为问题,我看了.NET source code。以下是来自IsValid MaxLengthAttribute方法的代码的相关部分,其中包含我的评论:

var str = value as string;   // Your type is decimal so str is null after this line
if (str != null) {
    length = str.Length;  // <- This statement is not executed
}
else {
    // Next line is where you must be receiving an exception:
    length = ((Array)value).Length;
}

答案 1 :(得分:1)

罪魁祸首是Maxlength

public function validate_passwords() 
{
     return $this->data[$this->alias]['password'] === $this->data[$this->alias]['confirm_password'];
}

对我来说很好。