2016-07-08 55 views
3

我在我的模型中有一个属性。当我提交表单时,我收到了以下错误。无法绑定Decimal属性在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> 
} 
+0

你可以发布视图和控制器的相关部分吗? –

+0

只是猜测,但它与你的'MaxLengthAttribute'有关吗? –

+1

除此之外,您正在使用RangeAttribute类的[this overload](https://msdn.microsoft.com/en-us/library/cc679307(v = vs.110).aspx)。我认为你需要使用[this overload](https://msdn.microsoft.com/en-us/library/cc679255(v = vs.110).aspx)。 – Rohit416

回答

4

您使用MaxLength属性,不带小数点的数据类型的工作。我不确定RegularExpression属性是否有效,但我没有验证。

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

只看到MaxLength可能是问题,我看了.NET source code。下面是从MaxLengthAttributeIsValid方法的代码的相关部分有我的评语:

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

它的作品,如果我删除MaxLength和范围。 – maxspan

+0

@maxspan然后,您将需要找到一种方法来实现使用其他属性进行验证。对于'Range',尝试使用其他超载属性,如@ Rohit416在您的问题 – dotnetom

+0

下提到的评论中提到的是我已经使用@ Rohit416技巧。不知道他为什么删除他的评论 – maxspan

1

罪魁祸首是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; } 
    } 

为我工作得很好。