I'm following this tutorial in order to insert multiple rows in my database. Following the exact code from the tutorial i was able to do it, but now i have a problem. My view:
<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>
And the script in the view:
<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>
In the tutorial, in the 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>
It uses @Html.TextBox instead of dropdownlist and editorfor, and in that way works, but in this way when i click to "Add more" it doesn't do anything, but i need to be able to use a dropdownlist and editorfor. I think i need to change something in the jquery but i don't know what since i'm new in that area. What do i need to change in order to make this work? Thanks in advance.