问题描述
我的要求是添加时间段设置,编辑和显示时间段 数据库中的字段是: 1.ID(短) 2.FromTime(时间跨度) 3.ToTime(时间跨度) 4.displayTime(字符串)
模型类:
public short TimeSlotID { get; set; }
public TimeSpan FromTime { get; set; }
public TimeSpan ToTime { get; set; }
数据库读取:
yield return new TimeSlotModel
{
TimeSlotID = reader.GetInt16("TimeSlotID"),FromTime = (TimeSpan)reader["FromTime"],ToTime = (TimeSpan)reader["ToTime"],displayText = reader.SafeGetString("displayText"),};
剃刀页面
<div class="row">
<div class="col">
<label for="TimeSlotID">TimeSlotID</label>
</div>
</div>
<div class="row">
<div class="col-4">
<label for="FromTime">FromTime</label>
</div>
<div class="col">
<label for="ToTime">ToTime</label>
</div>
</div>
<div class="form-group">
<div class="col">
<label for="displayText">displayText</label>
@item.displayText
</div>
</div>
I found it difficult to use any components to read and add or edit coz its Timespan .
i used datetimepicker but i dont kNow how to convert that to timespan while saving that to the database.Can anyone help solve this one.
谢谢!
解决方法
此解决方案绑定到用于设置模型时间跨度的 DateTimeOffset 属性。
Index.razor
@page "/"
<input type="time" @bind-value="FromTime" />
<input type="time" @bind-value="ToTime" />
<hr />
@ConvertTo12HourFormat(SomeModel.FromTime) - @ConvertTo12HourFormat(SomeModel.ToTime)
Index.razor.cs
using System;
using Microsoft.AspNetCore.Components;
public partial class Index : ComponentBase
{
readonly DateTimeOffset aDate = new DateTime(2020,01,01);
public SomeModel SomeModel { get; set; } = new SomeModel();
public DateTimeOffset FromTime
{
get { return aDate.Add(SomeModel.FromTime); }
set { SomeModel.FromTime = value.Subtract(aDate); }
}
public DateTimeOffset ToTime
{
get { return aDate.Add(SomeModel.ToTime); }
set { SomeModel.ToTime = value.Subtract(aDate); }
}
public string ConvertTo12HourFormat(TimeSpan time) => aDate.Add(time).ToString("hh:mm:ss tt");
}
SomeModel.cs
public class SomeModel
{
public short TimeSlotID { get; set; }
public TimeSpan FromTime { get; set; }
public TimeSpan ToTime { get; set; }
}