Blazor- EditForm InputCheckbox可为空的布尔问题解决

如何解决Blazor- EditForm InputCheckbox可为空的布尔问题解决

我正在尝试从输入库派生Blazor上的editform定制输入,但是由于最近才刚接触本周Blazor和本月的C#,因此我一直在努力掌握它。

我发现了 https://www.meziantou.net/creating-a-inputselect-component-for-enumerations-in-blazor.htm(或在下面找到粘贴的代码) 并能够将其用于inputselect内的可为空的枚举,但是尝试将其复制为可为空的输入复选框则无济于事。我想知道是否有人链接或会知道如何对其进行调整以使其正常工作。

提前谢谢您,我几乎整天都在我的电脑上,所以请随时提出问题,不要not惜我哈哈。

// file: Shared/InputSelectEnum.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using Humanizer;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;


// Inherit from InputBase so the hard work is already implemented ?
// Note that adding a constraint on TEnum (where T : Enum) doesn't work when used in the view,Razor raises an error at build time. Also,this would prevent using nullable types...
namespace OrderServiceFrontEnd.Shared
{
    public sealed class InputSelectEnum<TEnum> : InputBase<TEnum>
    {
        // Generate html when the component is rendered.
        protected override void BuildRenderTree(RenderTreeBuilder builder)
        {
            builder.OpenElement(0,"select");
            builder.AddMultipleAttributes(1,AdditionalAttributes);
            builder.AddAttribute(2,"class",CssClass);
            builder.AddAttribute(3,"value",BindConverter.FormatValue(CurrentValueAsString));
            builder.AddAttribute(4,"onchange",EventCallback.Factory.CreateBinder<string>(this,value => CurrentValueAsString = value,CurrentValueAsString,null));

            // Add an option element per enum value
            var enumType = GetEnumType();
            foreach (TEnum value in Enum.GetValues(enumType))
            {
                builder.OpenElement(5,"option");
                builder.AddAttribute(6,value.ToString());
                builder.AddContent(7,GetDisplayName(value));
                builder.CloseElement();
            }

            builder.CloseElement(); // close the select element
        }

        protected override bool TryParseValueFromString(string value,out TEnum result,out string validationErrorMessage)
        {
            // Let's Blazor convert the value for us ?
            if (BindConverter.TryConvertTo(value,CultureInfo.CurrentCulture,out TEnum parsedValue))
            {
                result = parsedValue;
                validationErrorMessage = null;
                return true;
            }

            // Map null/empty value to null if the bound object is nullable
            if (string.IsNullOrEmpty(value))
            {
                var nullableType = Nullable.GetUnderlyingType(typeof(TEnum));
                if (nullableType != null)
                {
                    result = default;
                    validationErrorMessage = null;
                    return true;
                }
            }

            // The value is invalid => set the error message
            result = default;
            validationErrorMessage = $"The {FieldIdentifier.FieldName} field is not valid.";
            return false;
        }

        // Get the display text for an enum value:
        // - Use the DisplayAttribute if set on the enum member,so this support localization
        // - Fallback on Humanizer to decamelize the enum member name
        private string GetDisplayName(TEnum value)
        {
            // Read the Display attribute name
            var member = value.GetType().GetMember(value.ToString())[0];
            var displayAttribute = member.GetCustomAttribute<DisplayAttribute>();
            if (displayAttribute != null)
                return displayAttribute.GetName();

            // Require the NuGet package Humanizer.Core
            // <PackageReference Include = "Humanizer.Core" Version = "2.8.26" />
            return value.ToString().Humanize();
        }

        // Get the actual enum type. It unwrap Nullable<T> if needed
        // MyEnum  => MyEnum
        // MyEnum? => MyEnum
        private Type GetEnumType()
        {
            var nullableType = Nullable.GetUnderlyingType(typeof(TEnum));
            if (nullableType != null)
                return nullableType;

            return typeof(TEnum);
        }
    }

}

Blazor comp:

<InputSelectEnum @bind-Value="@_Order.IOSAppDetails.PhasedRelease"/>

解决方法

作为[x]标签的替代方法,将该值设置为null

如果您希望在true,false,null之间循环,则可以强制OnChangeAction将值设置为null(如果以前是false)。

利用控件上的hidden属性来隐藏和显示<input><label>

@inherits InputBase<bool?>

<input type="checkbox" value="@CurrentValue" @attributes="AdditionalAttributes" class="@CssClass" style="width:15px; height:15px;vertical-align:-2px;"
       @onchange="EventCallback.Factory.CreateBinder<bool?>(this,OnChangeAction,this.CurrentValueAsBool)" hidden="@_HideCheckBox" />
<label @onclick="SetValueToTrue" hidden="@(!_HideCheckBox)" style="width:15px;height:15px;margin-left:-5px;">[?]</label>

@code {

    bool _HideCheckBox { get; set; } = false;

    bool? _CurrentValueAsBool;
    private bool? CurrentValueAsBool
    {
        get
        {
            if (string.IsNullOrEmpty(CurrentValueAsString))
                _CurrentValueAsBool = null;
            else
            {
                if (bool.TryParse(CurrentValueAsString,out bool _currentBool))
                    _CurrentValueAsBool = _currentBool;
                else
                    _CurrentValueAsBool = null;
            }

            SetCheckBoxCheckedAttribute(_CurrentValueAsBool);

            return _CurrentValueAsBool;
        }
        set => _CurrentValueAsBool = value;
    }


    void SetCheckBoxCheckedAttribute(bool? _currentValueAsBool)
    {
        bool _isChecked = _currentValueAsBool.HasValue ? _currentValueAsBool.Value : false;
        var _checkBoxAttributes = AdditionalAttributes != null ? AdditionalAttributes.ToDictionary(kv => kv.Key,kv => kv.Value) : new Dictionary<string,object>(); ;

        if (!_isChecked)
        {
            _ = _checkBoxAttributes.ContainsKey("checked") ? _checkBoxAttributes["checked"] = false : _checkBoxAttributes.TryAdd("checked",false);
            if (!_currentValueAsBool.HasValue)
                _HideCheckBox = true;
        }
        else
        {
            _HideCheckBox = false;
            _ = _checkBoxAttributes.ContainsKey("checked") ? _checkBoxAttributes["checked"] = true : _checkBoxAttributes.TryAdd("checked",true);
        }
        AdditionalAttributes = _checkBoxAttributes;
    }


    protected override bool TryParseValueFromString(string value,out bool? result,out string validationErrorMessage)
    {
        validationErrorMessage = null;

        if (string.IsNullOrEmpty(value))
        {
            result = null;
        }
        else
        {
            if (bool.TryParse(value,out bool _result))
            {
                result = _result;
            }
            else
            {
                validationErrorMessage = "Unable to parse value!";
                result = null;
                return false;
            }
        }
        return true;
    }

    private Action<Nullable<bool>> OnChangeAction
    {
        get => (_inputValue) =>
        {
            //ignore input value if previously false,to force it to null
            if (this.CurrentValueAsString == bool.FalseString)
            {
                _inputValue = null;
                this.CurrentValueAsString = string.Empty;
            }
            else
                this.CurrentValueAsString = _inputValue.HasValue ? _inputValue.Value.ToString() : string.Empty;
        };
    }

    void SetValueToTrue(MouseEventArgs e)
    {
        this.CurrentValueAsString = bool.TrueString;
    }

}

您可以将<label>更改为<image>或使用字体图标使其美观。

它看起来像这样: checkboxcycle

组件的使用保持不变。

@*.other fields.*@

<label>Nullable value:</label><NullableBoolCheckBox @bind-Value="someModel.SomeNullBoolValue" />
<br />
<strong>value is: @(someModel.SomeNullBoolValue.HasValue?$"{someModel.SomeNullBoolValue}":"null")</strong>
<br />

@*.other fields.*@
,

您可以继承InputBase<bool?>类并使用一些其他属性处理绑定值。

在此示例中,尽管看起来或多或少相同,但我没有使用“代码隐藏”方法。

该组件位于名为NullableBoolCheckBox.razor的文件中

@inherits InputBase<bool?>

<input type="checkbox" value="@CurrentValue" @attributes="AdditionalAttributes" class="@CssClass" style="width:15px; height:15px;vertical-align:-2px;"
       @onchange="EventCallback.Factory.CreateBinder<bool?>(this,this.CurrentValueAsBool)" />
<label @onclick="SetValueToNull" style="width:15px;height:15px;">[x]</label>

@code {

    bool? _CurrentValueAsBool;
    private bool? CurrentValueAsBool
    {
        get
        {
            if (string.IsNullOrEmpty(CurrentValueAsString))
                _CurrentValueAsBool = null;
            else
            {
                if (bool.TryParse(CurrentValueAsString,out bool _currentBool))
                    _CurrentValueAsBool = _currentBool;
                else
                    _CurrentValueAsBool = null;
            }

            SetCheckBoxCheckedAttribute(_CurrentValueAsBool);

            return _CurrentValueAsBool;
        }
        set => _CurrentValueAsBool = value;
    }


    void SetCheckBoxCheckedAttribute(bool? _currentValueAsBool)
    {
        bool _isChecked = _currentValueAsBool.HasValue ? _currentValueAsBool.Value : false;
        var _attributes = AdditionalAttributes != null ? AdditionalAttributes.ToDictionary(kv => kv.Key,object>(); ;

        if (!_isChecked)
        {
            _ = _attributes.ContainsKey("checked") ? _attributes["checked"] = false : _attributes.TryAdd("checked",false);
        }
        else
        {
            _ = _attributes.ContainsKey("checked") ? _attributes["checked"] = true : _attributes.TryAdd("checked",true);
        }
        AdditionalAttributes = _attributes;
    }

    protected override bool TryParseValueFromString(string value,out bool _result))
            {
                result = _result;
            }
            else
            {
                validationErrorMessage = "Unable to parse value!";
                result = null;
                return false;
            }
        }
        return true;
    }

    private Action<Nullable<bool>> OnChangeAction { get => (_inputValue) => CurrentValueAsString = _inputValue.HasValue ? _inputValue.Value.ToString() : null; }

    void SetValueToNull(MouseEventArgs e)
    {
        this.CurrentValueAsString = string.Empty;
    }
}

它可以与任何其他组件相同的方式使用。

例如:

<EditForm Model="someModel">

@*.more fields.*@

        <label>Nullable value:</label><NullableBoolCheckBox @bind-Value="someModel.SomeNullBoolValue" />
        <br />
        <strong>value is: @(someModel.SomeNullBoolValue.HasValue?$"{someModel.SomeNullBoolValue}":"null")</strong>

@*.more fields.*@

</EditForm>

链接到表单的模型具有属性:public bool? SomeNullBoolValue { get; set; },该属性绑定到复选框。

它看起来像这样: enter image description here

如果您不想使用[x]标签重设值,则可以执行诸如点击计数之类的操作来循环遍历值true,null

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res