我正在将 ASP MVC4 与 razor 一起使用,并且我必须将 View 中的一些信息返回到包含以下元素的列表中的 Controller ... 我使用 TextBox 来运行我的 js 函数...... 我使用以下 (updatesum()) javascript 在字段中动态计算我 View 中弓箭手得分的总和:
<td>
@Html.TextBox("suma["+@i+"]", Model[i].ArchScore1, new{ @onchange = "updatesum()"})
@Html.ValidationMessageFor(x => x[i].ArchScore1)
</td>
<td>
@Html.TextBox("sumb["+@i+"]", Model[i].ArchScore2, new { @onchange = "updatesum()" })
@Html.ValidationMessageFor(x => x[i].ArchScore2)
</td>
<td>
@Html.TextBox("sumt["+@i+"]", Model[i].ArchTot`enter code here`alScore, new { @onchange = "updatesum()" })
@Html.TextBoxFor(x=>x[i].ArchTotalScore)
@Html.ValidationMessageFor(x => x[i].ArchTotalScore)
</td>
<script type="text/javascript">
function updatesum() {
for (i = 0; i < 15; i++) {
var sua = "suma_" + i + "_";
var sub = "sumb_" + i + "_";
var sut = "sumt_" + i + "_";
suma = document.getElementById(sua).value;
sumb = document.getElementById(sub).value;
sum = (suma - 0) + (sumb - 0);
document.getElementById(sut).value = sum;
}
}
</script>
您知道将此 javascript 函数的结果添加到 TextBoxFor 中是否可行吗?
这是我建议修改后的代码:
<td>
@Html.TextBoxFor(m => m[i].ArchScore1, new{ @class = "score" })
@Html.ValidationMessageFor(x => x[i].ArchScore1)
</td>
<td>>
@Html.TextBoxFor(m => m[i].ArchScore2, new{ @class = "score" })
@Html.ValidationMessageFor(x => x[i].ArchScore2)
</td>
<td>
@Html.TextBoxFor(m => m[i].ArchTotalScore, new{ @class = "score" })
@Html.ValidationMessageFor(x => x[i].ArchTotalScore
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Save" />
</p>
}
<script type='text/javascript'>
$('.score').change(function () {
var inputs = $(this).closest('tr').find('input');
inputs.eq(2).val(new Number(inputs.eq(0).val()) + new Number(inputs.eq(1).val()));
});
</script>
第三个文本框仍未填充。
最佳答案
您可以使用以下脚本来更新行小计。为文本框指定类名称(例如 class="score"
)
$('.score').change(function() {
var inputs = $(this).closest('tr').find('input');
inputs.eq(2).val(new Number(inputs.eq(0).val()) + new Number(inputs.eq(1).val()));
});
但是您的代码中还有多个其他错误。首先,您手动覆盖输入的名称,因此当您发布时它不会绑定(bind)到您的模型。您需要更换
@Html.TextBox("suma["+@i+"]", Model[i].ArchScore1)
与
@Html.TextBoxFor(m => m[i].ArchScore1, new { @class = "score" })
其他文本框也是如此
您的总计文本框不应该是文本框(或者如果是文本框,那么它们应该被禁用),这样它们就不会回发。如果需要保存,必须在提交时在服务器上重新进行计算
关于javascript - 使用 TextBox 将数据(列表)从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31020911/