我試圖在每次向表單添加內容時在表格中添加一個新行的表格。這是我的代碼,然後我會告訴問題是什麼。MVC3在javascript中增加一個變量(jquery)
@{
//Declare the i variable
var i = 0;
}
@using (Html.BeginForm())
{
<table>
<tr>
<th>
</th>
<th>
Question
</th>
</tr>
<tr id="@(i+1)">
<td class="QuestionNum">
@(i+1))
</td>
//This is the cell with the Form field.
<td>
@Html.TextBoxFor(m => m.Questions[i].Question, new { @class = "QuestionBox Last" })
</td>
</tr>
</table>
}
<script>
$(document).ready(function() {
SetUpNewLine($('.QuestionBox'));
});
function SetUpNewLine(obj) {
obj.bind('keyup paste', function() {
if ($(this).val() != "") {
if ($(this).hasClass("Last")) {
//This is the line that isn't working.
@(i++)
$(this).parents('table').append('<tr id="@(i+1)"><td class="QuestionNum">@(i+1))</td><td>@Html.TextBoxFor(m => m.Questions[i], new { @class = "QuestionBox Last", style="width:100%;" })</td></tr>');
$(this).removeClass('Last');
SetUpNewLine($('.Last'));
}
});
}
</script>
所以,這個代碼工作的第一次,但在JavaScript函數調用@(i++)
時,一旦你的功能外它不保存變量的變化。因此,在第一個Html.TextBoxFor(用於Model.Questions對象中的第一個項目)之後,它確實創建了一個像我想要的新文本框,但不是增加它在List中更改的項目,而是使它們都只是編輯列表中的第二項。
奇怪的是,如果我要在$(document).ready()
內部做@(i++)
,那麼它可以正常工作。
關於如何正確增加變量的任何想法?我敢肯定,當涉及到混合Razor變量和Javascript時,我只是不知道。
那麼我會如何將變量放入HtmlHelper? – 2012-07-19 17:37:43
哦,所以在Javascript中,而不是使用HtmlHelper,我應該硬編碼,以便它適合回發模型? – 2012-07-19 17:41:08
是的。 MVC將使用模型聯編程序爲您填充模型。 – scottm 2012-07-19 17:42:59