如何在 Blazor 中将选定的日期时间选择器值转换为时间跨度 我的模型类:Timerazor.razor用于插入

问题描述

数据库中读取时,它会获得一个值。但是当我尝试添加一个新的时间段作为时间时(想要将其转换为时间跨度,因为数据库字段被声明为 Time(7) 所以格式为 hh:mm:ss:fffffff)我发现很难保存它。

我尝试了 datetimepicker,然后我也尝试了 time,但出现错误

我的模型类:

public class Model
{
  public short TimeSlotID { get; set; }
  public TimeSpan FromTime { get; set; }
  public TimeSpan ToTime { get; set; }
}

Timerazor.razor

<div class="row">
  <div class="col">
    <div id="datetimepicker-control">
       <!--<input type="time" name="FromTime" value="@item.FromTime.ToString("hh mm tt")" /> -->
    </div>
    <div class="col">
       <input type="time" name="FromTime" value="@item.ToTime.ToString("hh mm tt")" />
    </div>
@code
{
   // i dont kNow how to pass the timespan value while inserting the time. here.
    int rows = timeslotdal.InsertTimeSlot(modeltimeSlot);
}

用于插入

public int Insert(Model model)
{
   List<sqlParameter> parameters = new List<sqlParameter>()
   {
      new sqlParameter("@TimeSlotID",model.TimeSlotID),new sqlParameter("@FromTime",model.FromTime),new sqlParameter("@ToTime",model.ToTime),};

   return db.ExecuteNonQuery("storedproceduremodel",parameters);}
}

解决方法

您不能直接将 <input type='time'> 控件绑定到 C# TimeSpan,您需要添加一个绑定到 DateTime 的中间步骤,然后将值的时间元素通过到 TimeSpan 属性。

有关如何执行此操作的示例,请参阅 https://stackoverflow.com/a/54869699/41403