【发布时间】:2011-09-08 14:32:38
【问题描述】:
我正在使用 ASP.NET MVC 3。
我有文本框,我有一个控件来显示这些文本框之和的计算值。我使用 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 为空,但是当所有 4 个文本框都有值时,它具有添加文本框的值。为什么要这样做?我的代码中有什么不正确的地方吗?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-2