Segui este tutorial para poder inserir varios dados numa tabela da base de dados. Seguindo o tutorial consegui faze-lo, mas depois surgiu um problema.
A minha 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.UserTurmaId)</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>
E o script na minha 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>
No tutorial, no foreach da view, usam sempre @Html.TextBox mas eu preciso de usar um EditorFor e uma DropDownListFor. Com o TextBox funciona, mas quando tento usar o EditorFor e a DropDownListFor o botão de "Add More" não funciona. Penso que tenho de mudar algo no script mas nunca usei jquery antes. O que preciso de mudar para fazer isto funcionar? Obrigado.
↧