维护动态生成的复选框的状态
我正在使用 jquery 动态创建复选框列表。但是,当出现错误时,我需要保留复选框的状态。
我有这个工作,但似乎有点混乱:从发布的表单中获取值,将其放入视图状态,将视图状态变量的值放入隐藏字段,获取js中隐藏字段的值,将其拆分为一个数组,遍历该数组来比较 ID。
在我的控制器中:
if (ModelState.IsValid)
{
... stuff ...
}
else
{
ViewData["cbHack"] = Request.Form["cb_name"];
}
在我看来:
<%= Html.Hidden("cbHack",ViewData["cbHack"]) %>
和 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);
}
});
});
});
如何改进?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论