无法将十进制属性绑定到 MVC 中的视图

本文关键字:MVC 视图 绑定 十进制 属性 | 更新日期: 2023-09-27 17:55:46

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

无法将类型为"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>
}

无法将十进制属性绑定到 MVC 中的视图

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

尝试删除这两个属性,看看您的代码现在是否正常工作。如果是这样 - 您可能需要考虑一种使用其他属性的方法,这些属性可以与十进制类型一起正常工作(Range验证器似乎是一个很好的候选者)。

只是为了看看MaxLength是否可能是问题所在,我查看了 .NET 源代码。这是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;
}

罪魁祸首是Maxlength

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; }
    }

对我来说效果很好。