我正在使用jquery-maskmoney(https://github.com/plentz/jquery-maskmoney)作为货币输入字段。当我不使用掩码时,输入的值将传递给控制器,当我使用掩码时,我得到值0.
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Amount, new { htmlAttributes = new { @class = "form-control input-width-xlarge"} })
@Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
</div>
</div>
以下内容以连接该字段:
<script>
$(function() {
$('#Amount').maskMoney();
})
</script>
问题是,当使用掩码时,值0返回给控制器,当我不使用掩码时,我得到输入的值。
该字段的呈现HTML是
<input data-val="true" data-val-number="The field Amount must be a number." data-val-range="The field Amount must be between 0 and 10000000000." data-val-range-max="10000000000" data-val-range-min="0" data-val-required="The Amount field is required." htmlattributes="{ class = form-control input-width-xlarge }" id="Amount" name="Amount" type="text" value="0">
Controller方法是:
public ActionResult Create([Bind(Include = "ReceiptId,DonorId,Amount,CreationDate,CurrencyId,PaymentTypeId,AllocationId,LegacyAllocation,Activity,Diocese,Acknowledgement,Printed,OwnerId,LastUserId,LastUpdated,GiftAid,Notes")] CreateReceiptViewModel crvm)
我尝试使用EditorFor而不是TextBoxFor,结果相同。
答案 0 :(得分:2)
已解决:问题是视图模型中的数量是一个十进制但是返回了一个字符串,因此验证失败了。现在我考虑一下这是有道理的:)
解决方案是在视图模型中引入一个名为DisplayAmount的新String字段,并在视图中使用它。更改了绑定,以便它查找DisplayAmount,并在解析为Amount的操作中。
模型看起来像这样:
[Required]
[Range(0.0,10000000000)]
public Decimal Amount { get; set; }
[Required(ErrorMessage="Please supply the amount.")]
public String DisplayAmount { get; set; }
查看:
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.DisplayAmount, new { htmlAttributes = new { @class = "form-control input-width-xlarge"} })
@Html.ValidationMessageFor(model => model.DisplayAmount, "", new { @class = "text-danger" })
</div>
</div>
在行动中:
public ActionResult Create([Bind(Include = "ReceiptId,DonorId,DisplayAmount,CreationDate,CurrencyId,PaymentTypeId,AllocationId,LegacyAllocation,Activity,Diocese,Acknowledgement,Printed,OwnerId,LastUserId,LastUpdated,GiftAid,Notes")] CreateReceiptViewModel crvm) {
Decimal amount;
Decimal.TryParse(crvm.DisplayAmount, out amount);
crvm.Amount = amount;