【发布时间】:2015-09-14 08:11:33
【问题描述】:
我有一个使用 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 在 控制器 中调用 GetShiftsByStation
public 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") 但这不起作用,因为 .ToString("t") 在 LINQ 查询中当然不受支持。
【问题讨论】:
-
您使用的是哪个版本的实体框架?
-
如果您实现查询 -
db.Shifts.Where(...).ToList().Select(..)您可以使用string.Format方法。但无论如何,您应该返回一组匿名对象,而不是SelectList(客户端不知道 C#SelectList是什么),因此您的代码是不必要的额外开销(您创建了两次SelectList)和您发回的数据超出了必要范围 -
使用实体框架6
标签: c# .net entity-framework linq asp.net-mvc-5