I can't find words to explain without code, so here's what I got so far:
View: (bootstrap switch)
[...]
@foreach (var item in Model)
{
<tr>
<td>
<input class="my-checkbox" type="checkbox" name="my-checkbox" id="@(item.Id)" data-handle-width="100" data-on-text="Activer" data-off-text="Désactiver" data-size="small" data-on-color="success">
</td>
</tr>
}
[...]
<script type="text/javascript">
var isEnableUrl = '@Url.Action("IsEnabledMaterial", "MaterialType")';
$("[name='my-checkbox']").bootstrapSwitch();
</script>
Javascript:
$(document).ready(function () {
$('.my-checkbox').each(function (index) {
$.ajax({
type: 'POST',
url: isEnableUrl,
data: { 'id': index },
success: function (result) {
$('.my-checkbox').prop('checked', result);
},
error: function (e) {
swal("Error", "Can't modify that element. ", "error");
}
});
});
});
Then my controller:
[HttpPost]
public virtual bool IsEnabledMaterial(int id)
{
var materialType = materialTypeRepository.GetById(id);
return materialType.Enable;
}
So basically, what I'm trying to do, is on the load of the page, when all my "switch" are created, I want to go look in my database, to see which switch must be true or false and set them to the right value...
But when I'm trying to do that I get a NullReferenceException when the id = 0. Which is normal, I guess, 'cause in my database, the id's are 1, 2, 3 and 4. But if I increment by one the id, I get the same error when the id = 4. In every case, none of them get switch to true (they are all true in the DB). It will only work (for ids 1-2-3) if I do it manually (without .each), id: 0-4 are still failing to do what I want.
May it be with the foreach? 'Cause I tried passing the id "@(item.Id + 1)" and still got a 0 once...
Thanks very much for help!