【发布时间】:2021-12-16 05:59:51
【问题描述】:
我在 blazor 中有一个自定义 InputText 控件,可以很好地用于文本输入,但是 如果我将它绑定到十进制字段,它将不起作用并且我收到类型转换错误
这是我的代码:
这是我的模特
public class Quote
{
[Required]
public string TotalQuoteCost { get; set; }
}
这是我的自定义输入文本
@using System.Linq.Expressions
@inherits InputBase<string>
<div class=@ColumnLocation>
@if (!string.IsNullOrWhiteSpace(Label))
{
<label for="@Id">@Label</label>
}
<InputText @bind-Value="@CurrentValueAsString" class="form-control" placeholder="@Label"></InputText>
<ValidationMessage For="@ValidationFor" />
</div>
@code {
[Parameter] public string Id { get; set; }
[Parameter] public string Label { get; set; }
[Parameter] public Expression<Func<string>> ValidationFor { get; set; }
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
{
decimal gg = decimal.Parse(value);
result = String.Format("{0:n2}", gg);
validationErrorMessage = null;
return true;
}
}
这是页面:
@page "/counter"
<EditForm Model="quote" OnValidSubmit="@SubmitButtonPressed" class="form-horizontal">
<DataAnnotationsValidator />
<UxInputText Label="Quote cost" @bind-Value="quote.TotalQuoteCost"
ValidationFor="@(() => quote.TotalQuoteCost)"
/>
<button type="submit" class="btn">Check 1</button>
<h1>@ttt</h1>
</EditForm>
@code {
private string ttt = string.Empty;
Quote quote = new Quote();
protected void SubmitButtonPressed()
{
ttt = quote.TotalQuoteCost.ToString();
}
}
如果我将 TotalQuoteCost 定义为小数 (它必须是小数),我会收到以下错误:
1- CS1662 无法将 lambda 表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型
2- CS1503 参数 2:无法从“Microsoft.AspNetCore.Components.EventCallback”转换为“Microsoft.AspNetCore.Components.EventCallback”
3- CS0029 无法将类型“十进制”隐式转换为“字符串”
【问题讨论】:
-
看看这个。 meziantou.net/…
-
[礼貌] 问:你的目标是什么。您想构建一个包含标签、输入和验证消息的复合控件吗?如果是这样,有比从
InputBase继承包装器更简单的方法来实现这一点。或者你想用千位分隔符显示小数? -
我想构建一个复合控件,我想用小数显示“,”(千位分隔符),还想添加标签和验证。如果我更改模型字段的类型,它会起作用,但我不想这样做,因为它不是在数据库中使用字符串作为货币的好方法
-
@meziantou 请检查这里
标签: c# asp.net-core blazor blazor-webassembly