I'm using jquery to dynamically create a list of checkboxes. However, when there's an error, I need to preserve the state of the checkboxes.
I have this working, but it seems a bit kludgy: get the value from the posted form, put it into viewstate, put the value of the viewstate var into a hidden field, get the value of the hidden field in js, split it into an array, iterate thru the array comparing IDs.
In my controller:
if (ModelState.IsValid)
{
... stuff ...
}
else
{
ViewData["cbHack"] = Request.Form["cb_name"];
}
In my view:
<%= Html.Hidden("cbHack",ViewData["cbHack"]) %>
And the javascript:
$(document).ready(function() {
$("#TriggerDDL option:selected").each(function() {
$.getJSON('/controller/action/id', function(data, status) {
var foo = '<p>';
var selected = $('#cbHack').val().split(",");
if (data.length > 0) {
for (x in data) {
var d = data[x];
foo += "<input type='checkbox' name='cb_name' value='" + d.id + "'";
for (var s in selected) {
if (d.id == selected[s]) {
foo += " checked ";
$("#submit").removeAttr("disabled");
}
}
foo += ">" + d.text;
foo += "<br/>";
}
cb += "</p>";
$("#DynFoo").html(foo);
}
});
});
});
How can this be improved?