【发布时间】:2022-02-22 11:11:03
【问题描述】:
我想向我的 blazor 服务器应用程序的页面添加搜索功能,以允许用户按真、假或两者进行搜索。最初它是一个字符串 InputSelect 但现在我回到它我想将它更改为一个更整洁的解决方案,所以我试图制作一个自定义输入选择以从 InputSelect 继承,它将具有 3 个允许的值:true、false和空。我正在尝试将其绑定到布尔值?我的搜索模型类中名为 isVegetarian 的参数。
目前声明“result = null;”的行给出一个错误,因为“无法将 null 转换为类型参数 'TValue'。有没有办法可以在这个函数中返回 null?或者有更好的方法来做我想做的事吗?
这是制作自定义布尔值的尝试吗?输入选择:
// Start of code
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RecipeManager.Web.Shared
{
public class CustomNullableBoolInputSelect<TValue> : InputSelect<TValue>
{
protected override bool TryParseValueFromString(string value, out TValue result,
out string validationErrorMessage)
{
if (value.ToLower() == "null")
{
result = null;
validationErrorMessage = null;
return true;
}
if (typeof(TValue) == typeof(bool?))
{
if (bool.TryParse(value, out bool resultbool))
{
result = (TValue)(object)resultbool;
validationErrorMessage = null;
return true;
}
else
{
result = default;
validationErrorMessage =
$"The selected value {value} is not a valid bool?";
return false;
}
}
else
{
return base.TryParseValueFromString(value, out result,
out validationErrorMessage);
}
}
}
}
这里是调用它的地方:
<div class="col-12 row">
<label class="col-6">Vegetarian</label>
<CustomNullableBoolInputSelect class="form-control col-6" @bind-Value="searchModel.isVegetarian">
<option value="null" selected>All</option>
<option value="True">Vegetarian</option>
<option value="False">Not Vegetarian</option>
</CustomNullableBoolInputSelect>
</div>
【问题讨论】:
标签: c# blazor blazor-server-side