Reputation: 713
I got a checkbox list populated by my viewmodel. I specify id and value in the checkbox element. I need to save these information in the database. Currently i have it where i take the checkbox id and checkbox value, puts them in a key value pair and i intend to make an ajax call to my controller. Is there a better approach into doing this (mvc)? How would you do it? Thanks
My code:
VIEW
<div class = "divSubject">
@foreach (var item in Model.dictionarySubject)
{
<div>
@Html.CheckBoxFor(model => item.Value, new { @id = item.Key.subjectID})
@Html.DisplayFor(model => item.Key.subjectName)
</div>
}
</div>
JQuery
$("#btnSave").click(function () {
var dict = []; // create an empty array
$('.divSubject input[type=checkbox]').each(function () {
var id = $(this).attr('id')
dict.push({
key: id,
value: $(this).attr('checked')
});
alert(JSON.stringify(dict))
});
}
Upvotes: 0
Views: 2173
Reputation: 7872
Your code works just fine, but I believe that you want to take pairs of key and Boolean value. In this case, consider below code:
dict.push({
key: id,
value: !!$(this).attr('checked')
});
$(this).attr('checked') will return "checked" or null, not a Boolean value.
Upvotes: 1
Reputation: 1038710
The id of a DOM element has some limitations. For example it cannot start with a number. I would recommend you using the HTML5 data-* attributes to hold this metadata information:
@Html.CheckBoxFor(
model => item.Value,
new { data_id = item.Key.subjectID }
)
and then inside your javascript:
$('.divSubject input[type=checkbox]').each(function () {
var id = $(this).data('id')
dict.push({
key: id,
value: $(this).attr('checked')
});
alert(JSON.stringify(dict))
});
Other than that your code seems fine.
Upvotes: 1