我有一个使用jQuery脚本填充的级联下拉列表。列表中的每个项目我想显示代码和开始时间。类似的东西:
C123(早上7:30)
D345(上午9:00)
我无法确定如何格式化日期/时间以仅显示列表中的时间。
<script type="text/javascript">
$(document).ready(function () {
$("#Shift").prop("disabled", true);
//Dropdownlist Selectedchange event
$("#StationList").change(function () {
$("#Shift").empty();
if ($("#StationList").val() != "Select a Station") {
$.ajax({
type: 'POST',
url: '@Url.Action("GetShiftsByStation")', // we are calling json method
dataType: 'json',
data: { selectedValue: $("#StationList").val() },
// here we are get value of selected Station and passing same value as input to json method GetShifts.
success: function (shiftList) {
// states contains the JSON formatted list
// of shifts passed from the controller
$("#Shift").append('<option value="' + null + '">' + "Please select a shift" + '</option>');
$.each(shiftList, function (i, shift) {
$("#Shift").append('<option value="' + shift.Value + '">' + shift.Text + '</option>');
// here we are adding option for shifts
$("#Shift").prop("disabled", false);
});
},
error: function (ex) {
alert('Failed to retrieve shifts.' + ex);
}
});
return false;
}
else {
$("#Shift").empty();
$("#Shift").prop("disabled", true);
}
})
});
</script>
JQuery在控制器
中调用GetShiftsByStationpublic JsonResult GetShiftsByStation(string selectedValue)
{
//Created object of service class which holds the method that queries database.
DataAccess DataAccessService = new DataAccess();
//Created a list of string to hold shifts from Database.
List<SelectListItem> shiftList = new List<SelectListItem>();
//Populating the list by calling GetShiftsByStationId method of service class.
shiftList = DataAccessService.GetShiftsByStationId(Convert.ToInt32(selectedValue));
//Returning the list using jSon.
return Json(new SelectList(shiftList, "Value", "Text"));
}
调用GetShiftsByStationId(int stationId)查询数据库并返回每个位置的班次列表。
方式
//Gets the shift list based on StationId which is foreign key in Shifts table.
public List<SelectListItem> GetShiftsByStationId(int stationId)
{
//Created DataContext to query DB.
using (DataManager db = new DataManager())
{
//returns all the records from table based on StationId in list format.
return db.Shifts.Where(query => query.StationId == stationId).Select(s => new SelectListItem { Value = s.ShiftId.ToString(), Text = s.Code + " (" + s.Start + ")" }).ToList();
}
}
那么我在哪里以及如何最好地格式化从数据库返回的日期/时间?
我尝试使用 s.Start.ToString(“t”),但这当然不起作用。在LINQ查询中不支持.ToString(“t”)。
答案 0 :(得分:0)
使用此代替s.Start
DbFunctions.CreateTime(s.Start.Hour, s.Start.Minute, s.Start.Second)
如果您不使用EF6,请使用EntityFunctions
代替DbFunctions