我正在关注this tutorial以便在我的数据库中插入多行。按照教程中的确切代码我能够做到,但现在我遇到了问题。我的观点:
<style>
th {
text-align: left;
}
td {
padding: 5px;
}
</style>
<div style="width:700px; padding:5px; background-color:white;">
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div><a href="#" id="addNew">Add more</a></div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Aluno</th>
<th>Presente?</th>
<th></th>
</tr>
@if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
@if (Model != null && i.EventId != null && i.EventId != 0)
{
@Html.HiddenFor(a => a[j].EventId)
}
<td>@Html.DropDownListFor(a => a[j].UserCourseId, (SelectList)ViewBag.UserCourseId)</td>
<td>@Html.EditorFor(a => a[j].check)</td>
<td>
@if (j > 0)
{
<a href="#" class="remove">Remove</a>
}
</td>
</tr>
j++;
}
}
</table>
<input type="submit" value="Save Bulk Data" />
}
</div>
视图中的脚本:
<script language="javascript">
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('<a href="#" class="remove">Remove</a>');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
// Re-assign Validation
var form = $("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
// 2. Remove
$('a.remove').live("click", function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});
});
</script>
在教程中,在foreach中:
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td>@Html.DropDownListFor(a => a[j].UserCourseId, (SelectList)ViewBag.UserCourseId)</td>
<td>@Html.EditorFor(a => a[j].check)</td>
<td>
它使用@ Html.TextBox而不是dropdownlist和editorfor,并以这种方式工作,但这样当我点击“添加更多”它没有做任何事情,但我需要能够使用下拉列表和编辑。我想我需要在jquery中改变一些东西,但我不知道是什么,因为我是那个领域的新手。为了使这项工作,我需要改变什么?提前谢谢。