由于 jQuery datepicker 没有时间选择,我使用了下面的 TimeSpan 代码,它返回了小时 (0-23) 和分钟 (0-59) 的两个下拉列表。这工作正常。但是,我需要带有 AM/PM 下拉列表的 12 小时格式。
@model TimeSpan
@Html.DropDownList("hours", Enumerable.Range(0, 24)
.Select(i => new SelectListItem
{
Value = i.ToString(),
Text = i.ToString(),
//Selected = (Model.Hours > 12 ? Model.Hours - 12 : Model.Hours) == i
Selected = Model.Hours == i
}
))
@Html.DropDownList("minutes", Enumerable.Range(0, 60)
.Select(j => new SelectListItem
{
Value = j.ToString(),
Text = j.ToString(),
Selected=Model.Minutes == j
}
))
我添加了以下代码来显示 AM/PM 下拉列表。但是,我需要修改代码以使用 AM/PM 下拉列表显示 12 小时格式:
@Html.DropDownList("ampm", Enumerable.Range(0,2)
.Select(t => new SelectListItem
{
Value = t.ToString(),
Text = (t == 0 ? "AM" : "PM"),
Selected = (Model.Hours > 11 ? 1 : 0) == t
}
))
我需要帮助使用 AM/PM 下拉列表将以下 TimeBinder 类修改为 12 小时格式。
public class TimeBinder : IModelBinder
{
object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//Ensure there's incoming data
//*************************
//*** Validate "HOURS" ***
//*************************
var hoursKey = bindingContext.ModelName; //key = EODTime
var hoursValueProviderResult = bindingContext.ValueProvider.GetValue(hoursKey + ".hours"); //valueProviderResult = {15} (for selection of 15:10); RawValue has array of 15
if ((hoursValueProviderResult == null) ||
string.IsNullOrEmpty(hoursValueProviderResult.AttemptedValue))
{
return null;
}
//Preserve it in case we need to redisplay the form
bindingContext.ModelState.SetModelValue(hoursKey, hoursValueProviderResult);
//Parse
var hours = ((string[])hoursValueProviderResult.RawValue)[0];
//**************************
//*** Validate "MINUTES" ***
//**************************
var minuteKey = bindingContext.ModelName; //key = EODTime
var minutesValueProviderResult = bindingContext.ValueProvider.GetValue(minuteKey + ".minutes");
//valueProviderResult = {10} (for selection of 15:10); RawValue has array of 10
if ((minutesValueProviderResult == null) ||
string.IsNullOrEmpty(minutesValueProviderResult.AttemptedValue))
{
return null;
}
//Preserve it in case we need to redisplay the form
bindingContext.ModelState.SetModelValue(minuteKey, minutesValueProviderResult);
//Parse
var minutes = ((string[])minutesValueProviderResult.RawValue)[0];
//A TimeSpan represents the time elapsed sice midnight
var time = new TimeSpan(Convert.ToInt32(hours), Convert.ToInt32(minutes), 0);
return time;
}
}