如何将 bool 转换为字符串参数并在 Blazor 的字段中显示是或否

问题描述

这是我的类,我有一个布尔参数(在服务器端)

 public class ChassisDataInfo
{
    public string ChassisNo { get; set; }
    public string model { get; set; }
    public string type { get; set; }
    public bool warranty { get; set; }
}

在客户端,我将它绑定到 TextEdit,因为我想向客户端显示一个字符串。我的意思是,当我在 ChassisNumber 字段上输入数字时,保修应填写,但必须填写字符串,例如必须写成“It has”

          <Field>

            <TextEdit Placeholder="ChassisNumber" @bind-Text="ChassisNo"></TextEdit>

            <FieldLabel>warranty </FieldLabel>
            <TextEdit Text="@chassis.warranty.ToString()" disabled="true"> </TextEdit>
        
         <Button Color="Color.Primary" @onclick="@SearchChassis"> <Icon Name="IconName.Search"> 
         </Icon> </Button>
         </Field>
  Code{
   ChassisDataInfo chassis = new ChassisDataInfo();
     async Task SearchChassis()
    {
        chassis = await claim.GetChassisData(ChassisNo);
    }
   } 

解决方法

您可以在您的视图中做一个简单的检查:

<TextEdit Text="@(chassis.warranty?"Yes":"No")" Disabled="true"> </TextEdit>

或者您可能希望对 ChassisDataInfo 类进行更改并向其添加虚拟属性:

 public class ChassisDataInfo
{
    public string ChassisNo { get; set; }
    public string model { get; set; }
    public string type { get; set; }
    public bool warranty { get; set; }
    public virtual string hasWarranty => warranty ? "Yes" : "No";
}

然后你可以像这样使用它:

<TextEdit Text="@chassis.hasWarranty" Disabled="true"> </TextEdit>