【问题标题】:Microsoft.AspNetCore.Components.Forms.InputRadioGroup` does not support the type xxxMicrosoft.AspNetCore.Components.Forms.InputRadioGroup` 不支持类型 xxx
【发布时间】:2020-12-14 16:26:31
【问题描述】:

我想在 blazor 中使用单选组,因此在实现编辑表单并选择其中一个单选按钮后出现此错误:

Microsoft.AspNetCore.Components.Forms.InputRadioGroup`1[EGameCafe.SPA.Models.GameModel] 不支持“EGameCafe.SPA.Models.GameModel”类型。

这是我的编辑表单:

<EditForm Model="ViewModel" OnValidSubmit="HandleCreateGroup">

            @if (ViewModel.Games.List.Any())
            {
                <InputRadioGroup Name="GameSelect" @bind-Value="Gamemodelsample">
                    @foreach (var game in ViewModel.Games.List)
                        {
                        <InputRadio Value="game" />
                        @game.GameName
                        <br />
                        }
                </InputRadioGroup>
            }

</EditForm>

@code{
        public GameModel GameModelSample { get; set; } = new();
}

GameModel 是:

 public class GameModel
{
        public string GameId { get; set; }
        public string GameName { get; set; }
}


【问题讨论】:

    标签: asp.net-core blazor blazor-server-side


    【解决方案1】:

    InputRadioGroup 与其他 Blazor 组件一样,仅支持有限数量的类型,例如 StringInt32。您的想法是正确的,但不幸的是,您遇到了 Blazor 的一种限制。

    您可以尝试创建一个包装字段。

       private String _selectedGameId = "<Your Default Id>";
    
        public String SelectedGameId
        {
            get => _selectedGameId;
            set
            {
                _selectedGameId = value;
                // Set the property of the ViewModel used in your Model Property of the EditContext or any other property/field 
                ViewModel.SelectedGame = ViewModel.Games.List?.FirstOrDefault(x => x.GameId == value);
            }
        }
    
    

    使用属性SelectedGameId作为InputRadioGroup组件的绑定值。

    <InputRadioGroup Name="GameSelect" @bind-Value="SelectedGameId" >
                @foreach (var game in ViewModel.Games.List)
                {
                    <InputRadio Value="game.GameId" />
                    @game.GameName
                    <br />
                }
    </InputRadioGroup>
    

    作为替代方案,您可以创建一个继承自InputRadioGroup 的自定义组件以创建一种GameBasedInputRadioGroup。如果您有兴趣,我可以发布示例。

    【讨论】:

      【解决方案2】:

      因为在您的代码@bind-Value="Gamemodelsample" 中,您试图将GameName(string) 绑定到Gamemodelsaple(object),这将导致类型不匹配问题。

      您只需将代码修改为:

      @bind-Value="GameModelSample.GameName"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 2017-07-12
        • 2022-01-03
        相关资源
        最近更新 更多