I am developing a custom blazor select component. The component has a property named "Value" which in most cases is a string value which I can bind to using @bind-Value without any issues.
However in some situations the property which it binds to may be an integer (outside the component) in which case I need to convert from a string to an integer. I initially assumed simply using Int32.Parse would accomplish this as follows:
Select.razor.cs
namespace Accounting.Web.Components
{
public partial class Select
{
[Parameter]
public string Value { get; set; } = default!;
[Parameter]
public EventCallback<string>? ValueChanged { get; set; }
public void OnClick()
{
Value = "2";
ValueChanged?.InvokeAsync(Value);
}
}
}
Index.razor.cs
<Select Id="InvestmentEntitySelect" @bind-Value="@Int32.Parse(AddDto.InvestmentEntityId)">
@foreach (var entity in Entities)
{
<SelectOption Value="@entity.InvestmentEntityId.ToString()">@entity.Name</SelectOption>
}
</Select>
AddDto.cs
namespace Accounting.Shared.Dtos.Request.Investment
{
public class AddDto
{
[Required]
public int? InvestmentEntityId { get; set; } = 0;
[Required]
public string Description { get; set; } = String.Empty;
}
}
The line of interest is:
@bind-Value="@Int32.Parse(AddDto.InvestmentEntityId)"
But unfortunately this produces an error:
Argument 1: cannot convert from ‘int’ to ‘System.ReadOnlySpan’
So how can I converted the bind value to an integer in the above example?
2
Answers
You have to do it like this:
You need to create a custom input select like below and override the
TryParseValueFromString
method of it: