简体   繁体   English

如何将时间类型的输入与 blazor 绑定

[英]How to bind input of type time with blazor

Hello i have 2 variables of type int that i would like to bind to the min and max values of an input of type time .您好,我有2int类型的变量,我想将它们绑定到time类型的inputminmax
How can i do this?我怎样才能做到这一点?

I do not know what to place in the bind field since there are 2 different variables.我不知道在bind字段中放置什么,因为有 2 个不同的变量。 Also there is the min and max attributes.还有minmax属性。

<input type="time" min="@model.min" max="@model.max" bind=?/>

What should i put in the bind ?我应该在bind中放什么?

Update On a more thoroughly analysis i decided i will need 2 variables of type Timespan and i will bind these to 2 inputs of type time .更新在更彻底的分析中,我决定我需要 2 个Timespan类型的变量,并将它们绑定到 2 个time类型的输入。

You cannot bind a TimeSpan directly to an input in Blazor, but you can use a property to convert it to/from a string.您不能将 TimeSpan 直接绑定到 Blazor 中的输入,但可以使用属性将其转换为字符串/从字符串转换。

<input type="time" min="@model.min" max="@model.max" bind="@TimeProxy" />

and

@functions
{
  string TimeProxy { get => model.Time.ToString(); set => TimeSpan.TryParse(value,out model.Time); }
}

Previous solution was not working for me with .net Core 3.1 so I'll add an updated one:以前的解决方案不适用于 .net Core 3.1,因此我将添加一个更新的解决方案:

Use Blazor :使用 Blazor:

<EditForm Model=@model OnValidSubmit="Submit">
    <InputText type="time" @bind-Value="TimeProxy" />
</EditForm>

Code changes are necessary as well.代码更改也是必要的。

@code {
    // This field is required as you can not use property in out statement
    private TimeSpan LocalTime = TimeSpan.FromHours(0);
    private string TimeProxy { 
        get => model.Time.ToString();
        set => TimeSpan.TryParse(value,out LocalTime);
    }
    private void Submit() {
        model.Time = LocalTime;
        // following submit logic...
    }
}

I wrote a little component for this which utilizes databinding and works with the proper data types.我为此编写了一个小组件,它利用数据绑定并使用正确的数据类型。

usage:用法:

<LabeledTime @bind-Value="shutdownDelay"></LabeledTime>

component:零件:

<label class="form-label" for="@LabelId">
    @ChildContent
</label>
<input id="@LabelId" type="time" value="@ValueInternal.ToString("hh\\:mm")" step="60" @onchange="InternalValueChanged"/>

@code {

    private long LabelId = DateTime.Now.Ticks;

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public TimeSpan Value { get; set; }

    [Parameter]
    public EventCallback<TimeSpan> ValueChanged { get; set; }

    private TimeSpan ValueInternal { get; set; }

    protected override void OnParametersSet()
    {
        ValueInternal = Value;
        base.OnParametersSet();
    }

    private void InternalValueChanged(ChangeEventArgs obj)
    {
        if (!TimeSpan.TryParseExact(obj.Value.ToString(), "hh\\:mm\\:ss", null, out var result))
            return;

        ValueInternal = result;
        Value = result;
        ValueChanged.InvokeAsync(result);
    }
}

You can also do the following:您还可以执行以下操作:

<input type="time" @bind="SomeTime" @bind:format="HH:mm"/>

@code {
    public DateTime SomeTime = new DateTime();

    private TimeSpan _time = SomeTime.TimeOfDay;
}

Please not this doesn't bind to the TimeSpan directly!请注意,这不会直接绑定到 TimeSpan!

.NET 6.0.8 now has nice functionality for this in InputDate , that supports the TimeOnly type (among others). .NET 6.0.8 现在在InputDate中有很好的功能,它支持TimeOnly类型(等等)。 I found out as i was studying the .NET source code and about to create my own (due to ccStars' answer)我在研究 .NET 源代码并即将创建自己的源代码时发现(由于 ccStars 的回答)

<InputDate Type="InputDateType.Time" @bind-Value="@model.TimeVar" />

Where TimeVar has type TimeOnly? TimeVar的类型TimeOnly? . . It's nice that it handles nullable types.它处理可空类型很好。

Hopefully this helps, I was also trying to bind a Timespan a input of type="time" I managed to achieve it with the help from the following site https://www.meziantou.net/creating-a-inputselect-component-for-enumerations-in-blazor.htm希望这会有所帮助,我还尝试将 Timespan 绑定到type="time"的输入,我在以下站点https://www.meziantou.net/creating-a-inputselect-component-的帮助下设法实现了它blazor.htm 中的枚举

This is the code I created to achieve this这是我为实现这一目标而创建的代码
InputTime.cs输入时间.cs

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;
using System;
using System.Globalization;

namespace Example
{
    public sealed class InputTime : InputBase<TimeSpan>
    {
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {    
            builder.OpenElement(0, "input");
            builder.AddAttribute(1, "type", "time");
            builder.AddMultipleAttributes(2, AdditionalAttributes);
            builder.AddAttribute(3, "class", CssClass);
            builder.AddAttribute(4, "value", BindConverter.FormatValue(CurrentValueAsString));
            builder.AddAttribute(5, "onchange", EventCallback.Factory.CreateBinder<string>(this, value => CurrentValueAsString = value, CurrentValueAsString, null));
            builder.CloseElement(); // close the select element
        }
               
        protected override bool TryParseValueFromString(string value, out TimeSpan result, out string validationErrorMessage)
        {        
            validationErrorMessage = null;
            return BindConverter.TryConvertTo<TimeSpan>(value, CultureInfo.CurrentCulture, out result);
        }
    }
}

Razor Page剃刀页面

<div class="form-group">
    <label>Time From</label>
    <InputTime @bind-Value="MyModel.TimeFrom" class="form-control"></InputTime>
    <ValidationMessage For="() => MyModel.TimeFrom"></ValidationMessage>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Blazor NoobQuestion:How to shadow each keystroke enter in a<input type="“text”" @bind-value…> 住在上面的段落里? - Blazor NoobQuestion:How to shadow each keystroke entered in a <Input type=“text” @bind-value… /> live in the paragraph above? 删除输入文本的所有内容,Blazor 中没有@bind - Delete all content of input text, without @bind in Blazor 如何在HTML中绑定数量(类型编号的输入)和项目(类型复选框的输入)? - How can I bind quantity (input of type number) and item (input of type checkbox) in HTML? jQuery:如何使用值<input type =“time”> - jquery: how to use value of <input type =“time”> 如何在CSS指标中进行选择 <input type=“time”> ? - How to select with css indicator in <input type=“time”>? 角度:如何在初始化时将时间类型的输入设置为当前时间 - Angular: how to set input of time type to current time on initialization 输入类型时间的格式化时间 - Format time of input type time Blazor WASM .NET 5 输入时间不正确显示 - Blazor WASM .NET 5 input time do not show correctly 如何清除 Blazor 服务器应用程序中的文本类型输入字段? 清除相关字符串变量时字段未清除 - How can I clear a text type Input field in my Blazor server app? The field is not cleared when I clear the related string variable 如何在禁用的输入类型=“时间”元素上将数字居中? - How do I center the digits on a disabled input type=“time” element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM