在复选框中获取默认值
本文关键字:默认值 获取 复选框 | 更新日期: 2023-09-27 17:58:06
我在函数中有一个下拉复选框。因此,用户可以选择一个、多个或零个。当用户选择一个或多个时,一切都是正确的。但是当用户没有选择任何一个时,我会有一个空指针异常。为了处理这个异常,我想默认情况下,如果他没有选择任何东西来显示所有结果(就像他选择所有一样)。我该怎么做?
这是JS函数
$(function () {
$("#datepicker").datepicker({
//defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
minDate: "01/01/2008"
})
.datepicker('setDate', new Date());
$("button.action").click(function () {
//var users = new Array();
var date = $('#datepicker').val().toString();
var selected_values = new Array();
//var userName = $(' .checked:checked').val();
$(document).ready(function () {
selected_values = []; // initialize empty array
$(".checked:checked").each(function () {
selected_values.push($(this).val());
});
});
$.ajax({
url: 'EmployeeDate',
datatype: "application/json",
traditional:true,
data: {
lstUserName: selected_values,
strDate: date
},
success: function (data, textStatus, jqXHR) {
$('#DataUser').html(data);
},
error: function () {
console.log("error handler when ajax request fails... ");
},
});
});
});
这就是控制器:
public IEnumerable<DateTime> getInfoByDate(string strDate, string[] lstUserName)
{
CareDB context = new CareDB();
IEnumerable<DateTime> lst = null;
List<DateTime> model = new List<DateTime>();
if (lstUserName != null)
{
foreach (string user in lstUserName)
{
SqlParameter userName = new SqlParameter("@EmployeeName", user);
SqlParameter Date = new SqlParameter("@Date", strDate);
object[] parameters = new object[] { Date, userName };
model.Add(context.ReleaseDate.SqlQuery("_UserInformationByDate @Date, @EmployeeName", parameters).ToList().FirstOrDefault());
}
}
else
{
SqlParameter Date = new SqlParameter("@Date", strDate);
SqlParameter userName = new SqlParameter("@EmployeeName", lstUserName);
object[] parameters = new object[] { Date, userName };
model = context.ReleaseDate.SqlQuery("_UserInformationByDate @Date, @EmployeeName", parameters).ToList();
}
context.Dispose();
context = null;
return model;
}
试试这个
$(document).ready(function () {
selected_values = []; // initialize empty array
// nothing selected so push all value regadless
if( $(".checked:checked").length == 0)
{
$(".checked").each(function () {
selected_values.push($(this).val());
});
}
else
{
$(".checked:checked").each(function () {
selected_values.push($(this).val());
});
});
}