我使用ASP.NET MVC 3.天冬氨酸MVC结合计算结果从jQuery来建模
我有文本框和我有一个显示这些文本框的总和的计算值的控制。我使用jQuery来计算这些结果。
我很努力回帖,然后总数被清除,我不知道它如何保留计算结果。所以我认为,如果我在视图模型中有一个属性,那么它将在回发后保留该值。我试着使用Html.TextboxFor作为总数,当我点击提交按钮时,这似乎成了价值。但我不希望它是一个文本框,只是文本,但我仍然需要它绑定到视图模型。我的视图模型的
部分:
public class EditGrantApplicationViewModel
{
public decimal? GrossMonthlySalary { get; set; }
public decimal? SpouseGrossMonthlySalary { get; set; }
public decimal? AdditionalIncome { get; set; }
public decimal? ChildSupportIncome { get; set; }
public decimal? TotalMonthlyIncome
{
get { return totalMonthlyIncome; }
set
{
totalMonthlyIncome = GrossMonthlySalary +
SpouseGrossMonthlySalary +
AdditionalIncome +
ChildSupportIncome;
}
}
}
我的HTML的部分:
<td><label>Gross Monthly Salary:</label> <span class="red">**</span></td>
<td>@Html.TextBoxFor(x => x.GrossMonthlySalary, new { @class = "income", maxlength = "10", size = "20" })
@Html.ValidationMessageFor(x => x.GrossMonthlySalary)
</td>
<td><label>Spouse Gross Monthly Salary:</label></td>
<td>@Html.TextBoxFor(x => x.SpouseGrossMonthlySalary, new { @class = "income", maxlength = "10", size = "20" })
@Html.ValidationMessageFor(x => x.SpouseGrossMonthlySalary)
</td>
<td><label>Any Additional Income:</label></td>
<td>@Html.TextBoxFor(x => x.AdditionalIncome, new { @class = "income", maxlength = "10", size = "20" })
@Html.ValidationMessageFor(x => x.AdditionalIncome)
</td>
<td><label>Child Support Received:</label></td>
<td>@Html.TextBoxFor(x => x.ChildSupportIncome, new { @class = "income", maxlength = "10", size = "20" })
@Html.ValidationMessageFor(x => x.ChildSupportIncome)
</td>
<td><label class="total">Total Monthly Income:</label></td>
<td>
<label id="TotMonthlyIncome" class="total-amount">@Html.DisplayTextFor(x => x.TotalMonthlyIncome)</label>
@Html.HiddenFor(x => x.TotalMonthlyIncome)
</td>
的jQuery的补充:
$('.income').keyup(function() {
var incomes = $('.income'),
totDisplay = $('#TotMonthlyIncome'),
totalDisplay = $('#TotalMonthlyIncome'),
totalVal = 0;
incomes.each(function() {
var matches = null;
// find the number to add to total
matches = $(this).val().match(/\d+/);
// not bothering with the regex on totalVal because we set it
totalVal = (matches !== null ? parseInt(matches[0], 10) : 0) + parseInt(totalVal, 10);
});
totalVal = totalVal === 0 ? '' : totalVal;
totDisplay.text(totalVal);
$('#TotalMonthlyIncome').val(totalVal);
});
当我的值在文本框中键入那么它计算正确。如果我在4个文本框中输入值,那么它的计算是正确的。如果我在1个文本框中输入一个值,那么TotalMonthlyIncome为null,但是当所有4个文本框中都有值时,它具有文本框添加的值。它为什么这样做?这是不是在我的代码是正确的?
谢谢。 HasValue和Value属性仅用于可空类型? –
@Brendan Vogt,它只适用于'System.Nullable'类型,这就是你正在使用的类型。 –