使用TextBox将数据(列表)从视图传递到控制器

时间:2015-06-24 07:58:00

标签: javascript asp.net asp.net-mvc asp.net-mvc-4 razor

我正在使用带有剃刀的ASP MVC4而且我坚持将我的视图中的一些信息返回到我的控制器中,并列出以下元素... 我使用TextBox来运行我的js函数... 我使用以下(updatesum())javascript在我的视图中动态计算射手得分的总和:

<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>

仍未填充第3个文本框。

1 个答案:

答案 0 :(得分:1)

您可以使用以下脚本更新行小计。为文本框指定一个类名(比如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()));
});

您的代码中有多个其他错误。首先,您手动覆盖输入的名称,以便在发布时不会绑定到您的模型。你需要更换

@Html.TextBox("suma["+@i+"]", Model[i].ArchScore1)

@Html.TextBoxFor(m => m[i].ArchScore1, new { @class = "score" })

和其他文本框同上

总计的文本框不应该是文本框(或者如果它们应该被禁用),所以它们不会回发。如果您需要保存它们,则必须在提交时再次在服务器上完成计算