AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[blazor](coding)

Martin Hope
jass
Asked: 2025-04-27 02:07:37 +0800 CST

为什么 Blazor Server .NET 9 显示 QuickGrid 缺少引用

  • 6

我尝试在 Blazor Web 应用和服务器中使用 QuickGrid。但代码总是显示“程序集缺失”。我按照文档中的所有步骤操作并应用了它,但仍然显示


命名空间dotnet 添加包 Microsoft.AspNetCore.Components.QuickGrid中缺少 QuickGrid

我已经安装了该 nuget 包:

nuget包

@using Microsoft.AspNetCore.Components.QuickGrid

错误图像

blazor
  • 1 个回答
  • 39 Views
Martin Hope
sTx
Asked: 2025-03-28 15:17:53 +0800 CST

.NET 9 上的 Blazor Interactive Server:InputRadioGroup 重新渲染页面但不保留选定的选项

  • 6

我需要根据单选按钮选择显示不同的组件,因此我使用此处InputRadioGroup描述的方法。

当选择任一选项时,页面会重新渲染,并显示正确的组件,但InputRadioGroup会再次重新渲染,并且不会保留选择。我尝试过放入, InputRadioGroup但<EditForm Model="ColorInt"发生了同样的事情。我甚至尝试过这种checked="@(ColorInt == 1)"方法,但它也不起作用。这是一个已报告的错误,已在 .NET 7 中解决,但它仍然发生在我身上。

<InputRadioGroup Name="color" @bind-Value="ColorInt">
    Colors:
    <div style="margin-bottom:5px">
        <div>
            <label>
                <InputRadio Name="color" Value="1" checked="@(ColorInt == 1)" />
                Red
            </label>
        </div>
        <div>
            <label>
                <InputRadio Name="color" Value="2" checked="@(ColorInt == 2)" />
                Green
            </label>
        </div>
        <div>
            <label>
                <InputRadio Name="color" Value="3" checked="@(ColorInt == 3)" />
                Blue
            </label>
        </div>
    </div>
</InputRadioGroup>

@switch (ColorInt)
{
     case 1: { <red /> break; }
     case 2: { <green/> break; }
     case 3: { <blue/> break; }   
}

@code {
    private int ColorInt{ get; set; } = 1;
}

PS 这只是我的愚蠢行为...因为需要编辑我的实际代码,所以我从未检查过这一点。我的代码Value实际上来自一个静态类MagicStrings,该类保存了我整个应用程序的一些const值。

<InputRadio Name="color" Value="@MagicStrings.RedColor" />

现在MagicStrings.RedColor类型是byte

public const byte RedColor = 1;
@code {
    private int ColorInt{ get; set; } = @MagicStrings.RedColor; // which was byte
}
blazor
  • 1 个回答
  • 32 Views
Martin Hope
John D
Asked: 2025-01-19 05:30:22 +0800 CST

我们如何引用 HeaderTemplate 来使用 RenderFragment 为 QuickGrid 指定 HTML?

  • 6

我们在 VS 2022 中有一个 .NET 8 和 C# Blazor 项目,其中包含许多 QuickGrids。

我想使用 来放置PropertyColumn的标题文本的 HTML 和样式HeaderTemplate,这将覆盖该Title字段。但我不知道如何使用HeaderTemplate。

我的 QuickGrid 标记如下所示:

<PropertyColumn 
         Property="f => f.TXT_NAME"              
         HeaderTemplate="<TemplateHeader>Missouri</TemplateHeader>" 
         Sortable="false" Class="itemName" />

我已在 Google 上搜索了指定/利用该HeaderTemplate功能的正确方法的示例,但找不到任何示例。您在上面的代码中看到的是关于如何使用的无效猜测HeaderTemplate。

当我输入代码时HeaderTemplate,VS 2022 会立即跟进=""-- 暗示应该输入一些文本。但是……我尝试了各种方法,你可以看到我尝试提供一个包含渲染片段的组件 -- 但编译时不会出现错误

无效的表达式术语“<”

我陷入困境。

渲染片段组件标记和代码如下:

<div class="text-danger fst-italic fw-bold">
   @ChildContent
</div>

@code {
#pragma warning disable CS8618
   [Parameter] public RenderFragment? ChildContent { get; set; }
#pragma warning restore CS8618
}
      

欢迎您提出解决方案、评论和问题。

谢谢。

blazor
  • 2 个回答
  • 32 Views
Martin Hope
max
Asked: 2025-01-12 09:15:19 +0800 CST

Blazor WebAssembly 应用程序中的 HttpClient 注入问题

  • 7

我有一个 ASP.NET Core Web API 项目作为后端,还有一个 Blazor Web 程序集作为前端。

Web API 可ProductController返回 JSON 数据(产品、组等)。Blazor 应用使用该 API。

ProductService我在 Blazor 端创建。ProductService获取HttpClient构造函数注入并向 API 发送请求。这就是问题所在——我收到 404 NotFound 错误。当我使用注入HttpClient或直接在页面上创建它时,它可以工作(请参阅下面显示的代码)。

如果我在浏览器中输入 API URL,我会得到数据(产品目录)。我HttpClient按照 Microsoft在文章中所说的进行初始化。请帮助解决这个问题。

这是 Blazor 初始化代码:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var appSettings = builder.Configuration.Get<AppSettings>();
builder.Services.AddSingleton<AppSettings>(appSettings);

builder.Services.AddBlazoredLocalStorage();

builder.Services.AddHttpClient("Shop.WebApi", client => client.BaseAddress =
    new Uri(appSettings.ApiBaseUri))
         .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("Shop.WebApi"));
builder.Services.AddApiAuthorization();

builder.Services.AddScoped<CustomAuthenticationStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(
    provider => provider.GetRequiredService<CustomAuthenticationStateProvider>());
builder.Services.AddScoped<AuthService>();
builder.Services.AddHttpClient<IProductService, HttpProductService>(client =>
{
    client.BaseAddress = new Uri(appSettings.ApiBaseUri);
}).AddHttpMessageHandler<CustomAuthorizationMessageHandler>();

await builder.Build().RunAsync();

这是产品目录页面:

@inject IProductService ProductService
@inject HttpClient TheHttpClient
...
protected override async Task OnInitializedAsync()
{
    try
    {
    // this works   
        _ProductCatalog = await TheHttpClient.GetFromJsonAsync<ProductCatalog>("api/Product/GetProductCatalog");
    // this doesn't work
        //await LoadProductCatalogAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred while initializing the page: " + ex.Message);
    }
}

private async Task LoadProductCatalogAsync()
{
    try
    {
        _ProductCatalog = await ProductService.GetProductCatalog();
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred while loading the product catalog: " + ex.Message);
    }
}

产品服务:

public class HttpProductService : IProductService
{
    public HttpProductService(HttpClient httpClient)
    {
        TheHttpClient = httpClient;
    }

    public async Task<ProductCatalog> GetProductCatalog()
    {        
        var response = await TheHttpClient.GetAsync($"{GetApiBaseUri()}");

        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadFromJsonAsync<ProductCatalog>();
        }

        return new ProductCatalog();
    }

    protected virtual string GetApiBaseUri() => $"api/Product";
    protected HttpClient TheHttpClient { get; }
}
blazor
  • 1 个回答
  • 37 Views
Martin Hope
DrXSsive
Asked: 2025-01-08 21:04:44 +0800 CST

Blazor FluentDataGrid 中的分页功能无法正常工作

  • 5

我正在尝试使用 FluentDataGrid 显示数据,但出现了非常奇怪的行为。问题:

  1. 网格的总项目数未正确更新。这就是分页按钮不起作用的原因。
  2. 我以某种方式设法设置了总项目数,但是当我更改页面时,事件总是获得 0 作为页码。

这是我的代码。我使用@rendermode = InteractiveAssembly。

@rendermode InteractiveWebAssembly

@inject HttpClientService httpClientService

<FluentDataGrid Items="RolesData?.Data?.AsQueryable()"
                TGridItem="GetRoles.Response"
                Pagination="paginationState"
                ShowHover="true"
                MultiLine="true"
                Loading="@gridLoader">
    <PropertyColumn Property="@(c => c.Name)" Sortable="false" />
    <TemplateColumn Title="Permissions">
        <p>@context.PermissionCount permissions assigned</p>
    </TemplateColumn>
    <TemplateColumn Title="Assigned To">
        <p>@context.AssignedTo uers</p>
    </TemplateColumn>
    <TemplateColumn Title="Actions">
        @if (context.IsPrimary == false)
        {
            <FluentButton aria-label="Edit item" IconEnd="@(new Icons.Regular.Size16.Edit())" OnClick="() => OnEditClick(context.Id)" />
            <FluentButton aria-label="Delete item" IconEnd="@(new Icons.Regular.Size16.Delete())" OnClick="() => OnDeleteClick(context.Id)" />
        }
    </TemplateColumn>
</FluentDataGrid>
<FluentPaginator State="@paginationState" CurrentPageIndexChanged="OnCurrentPageIndexChanged" />

这是我的组件。我最初在 OnAfterRenderAsync 上获取数据

private GetRoles.Request request = new GetRoles.Request();
private Pagination.Response<IEnumerable<GetRoles.Response>>? RolesData;

PaginationState paginationState = new PaginationState { ItemsPerPage = 10 };
bool gridLoader;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await GetRoles();
    }
}

private async Task GetRoles()
{
    gridLoader = true;
    StateHasChanged();

    request.Page = paginationState.CurrentPageIndex;
    request.PageSize = paginationState.ItemsPerPage;

    var roleDataResponse = await httpClientService.GetAsync<Pagination.Response<IEnumerable<GetRoles.Response>>>("/api/roles", request);
    if (roleDataResponse != null)
    {
        RolesData = roleDataResponse;

        await paginationState.SetTotalItemCountAsync(roleDataResponse.TotalRecords);
    }

    gridLoader = false;
    StateHasChanged();

    Console.WriteLine($"CurrentPageIndex: {paginationState.CurrentPageIndex}");
    Console.WriteLine($"LastPageIndex: {paginationState.LastPageIndex}");
    Console.WriteLine($"TotalItemCount: {paginationState.TotalItemCount}");
}

处理分页按钮点击的事件是

async void OnCurrentPageIndexChanged(int index)
{
    await paginationState.SetCurrentPageIndexAsync(index);
    await GetRoles();
}

这是 API 返回的数据

{
    "totalRecords": 11,
    "data": [
        {
            "id": "Dy9dkGzW",
            "name": "Test 9",
            "permissionCount": 2,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "eV9ablPg",
            "name": "Test 8",
            "permissionCount": 2,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "X892olBV",
            "name": "Test 7",
            "permissionCount": 10,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "8e7V896p",
            "name": "Test 6",
            "permissionCount": 1,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "1VGx2l5Q",
            "name": "Test 5",
            "permissionCount": 4,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "5Y7Qq7Bk",
            "name": "Test 4",
            "permissionCount": 9,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "O8l1wGqx",
            "name": "Test 3",
            "permissionCount": 2,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "Y8Gb39Bq",
            "name": "Test 2",
            "permissionCount": 3,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "QY7BV7OV",
            "name": "Test 1",
            "permissionCount": 2,
            "assignedTo": 0,
            "isPrimary": false
        },
        {
            "id": "ZYG8o71v",
            "name": "Finance",
            "permissionCount": 8,
            "assignedTo": 0,
            "isPrimary": false
        }
    ]
}

如您所见,这里的“totalRecords”为 11。分页应该显示总记录数为 11,并且应该有 2 页,但它向我显示了这个 在此处输入图片描述

如果我将“await paginationState.SetTotalItemCountAsync(roleDataResponse.TotalRecords);”移到方法的末尾,它会正确设置总项目数,并且分页按钮不会被禁用,但是当我单击下一个按钮时,事件处理程序在“索引”中获取 0。

我是不是漏掉了什么,或者做错了什么?任何帮助都将不胜感激。

先感谢您。

blazor
  • 1 个回答
  • 41 Views
Martin Hope
Ahmad Salim
Asked: 2025-01-01 16:20:40 +0800 CST

Blazor .NET 8 Web 应用服务器双向绑定未绑定到模型且未触发事件

  • 6

我在 Blazor Server 应用程序中使用 Syncfusion 的 SfTextBox 组件。我已将其绑定@bind-Value到模型中的属性,并添加了ValueChange事件以添加其他逻辑。

但是,ValueChange事件未触发,并且绑定属性仍然为空。

    <SfTextBox @bind-value=@Value
               Placeholder=@Placeholder
               Enabled=@IsEnabled
               [email protected]
               CssClass="" />
public partial class SignInComponent : ComponentBase
{
      [Inject]
      public IIdentityViewService IdentityViewService { get; set; }

      [Inject]
      public AuthenticationStateProvider AuthStateProvider { get; set; }

      public ComponentState State { get; set; }
      public IdentityComponentException Exception { get; set; }

      public SignInView SignInView { get; set; }
      public TextBoxBase SignInEmailTextBox { get; set; }
      public TextBoxBase SignInPasswordTextBox { get; set; }
      public ButtonBase SubmitButton { get; set; }
      public SpinnerBase Spinner { get; set; }

      protected override void OnInitialized()
      {
          SignInView = new SignInView();
          State = ComponentState.Content;
      }
}
public partial class TextBoxBase : ComponentBase
{
     [Parameter]
     public string Value { get; set; }

     [Parameter]
     public string Placeholder { get; set; }

     [Parameter]
     public string CssClass { get; set; }

     [Parameter]
     public EventCallback<string> ValueChanged { get; set; }

     [Parameter]
     public bool IsDisabled { get; set; }

     public bool IsEnabled => IsDisabled is false;

     public async Task SetValue(string value)
     {
         this.Value = value;
         await ValueChanged.InvokeAsync(this.Value);
     }

     private Task OnValueChanged(ChangeEventArgs changeEventArgs)
     {
         this.Value = changeEventArgs.Value.ToString();
         //InvokeAsync(StateHasChanged);
         return ValueChanged.InvokeAsync(this.Value);
     }

     public void Disable()
     {
         this.IsDisabled = true;
         InvokeAsync(StateHasChanged);
     }

     public void Enable()
     {
         this.IsDisabled = false;
         InvokeAsync(StateHasChanged);
     }
}
<div class="py-6 flex flex-col gap-5">
    <div>
        <TextBoxBase
             @ref=@SignInEmailTextBox
             @[email protected]
             Placeholder="Your email ?"
             CssClass="w-full py-3 px-6 ring-1 ring-gray-300 rounded-xl placeholder-gray-600 bg-transparent transition disabled:ring-gray-200 disabled:bg-gray-100 disabled:placeholder-gray-400 invalid:ring-red-400 focus:invalid:outline-none" />
    </div>
    <div class="flex flex-col items-end">
        <TextBoxBase 
             @ref=@SignInPasswordTextBox
             @[email protected]
             Placeholder="What's the secret word ?"
             CssClass="w-full py-3 px-6 ring-1 ring-gray-300 rounded-xl placeholder-gray-600 bg-transparent transition disabled:ring-gray-200 disabled:bg-gray-100 disabled:placeholder-gray-400 invalid:ring-red-400 focus:invalid:outline-none" />
           <a href="/forgotten/password" type="reset" class="w-max p-3 -mr-3">
               <span class="text-sm tracking-wide text-blue-600">Forgot password ?</span>
           </a>
    </div>
    <div>
        <ButtonBase 
               @ref=@SubmitButton 
               OnClick=@SignInAsync 
               Label="Login"
               CssClass="w-full px-6 py-3 rounded-xl bg-sky-500 transition hover:bg-sky-600 focus:bg-sky-600 active:bg-sky-800" />
        <SpinnerBase @ref=@Spinner />
    </div>
</div>
blazor
  • 2 个回答
  • 38 Views
Martin Hope
user3776241
Asked: 2024-11-17 04:27:02 +0800 CST

FluentEditForm 说没有数据,尽管输入了数据

  • 6

下面是我的代码,一个 fluenteditform 表单。提交后,系统提示我填写了字段,但仍然需要填写。我的代码有什么问题?

@page "/movieform" 
@using Assignment10.Entities
@using System.ComponentModel.DataAnnotations

<h3>MovieForm</h3>

<FluentCard>
    <FluentEditForm FormName="MovieForm" Model="@movie">
        <DataAnnotationsValidator />
        <FluentValidationSummary />
        <FluentGrid>
            <FluentGridItem xs="12">
                <FluentTextField Name="MovieNameField" Id="movieNameField" @bind-Value="movie.MovieName" Label="Name: " Required/>
                <ValidationMessage For="@(() => movie.MovieName)" />
            </FluentGridItem>
            <FluentGridItem xs="12">
                <FluentTextField Name="MoviePublisherField" Id="moviePublisherField" @bind-Value="movie.Publisher" Label="Publisher: " Required/>
                <ValidationMessage For="@(() => movie.Publisher)" />

            </FluentGridItem>
            <FluentGridItem xs="12" >
                <FluentTextField Name="MovieDescriptionField" Id="movieDescriptionField" @bind-Value="movie.MovieDescription" Label="Description: " Required/>
                <ValidationMessage For="@(() => movie.MovieDescription)" />
            </FluentGridItem>
            <FluentGridItem xs="12" >
                <FluentButton Type="ButtonType.Submit" Appearance="Appearance.Accent">Submit</FluentButton>
            </FluentGridItem>
        </FluentGrid>
    </FluentEditForm>
</FluentCard>

@code {
    private Movie movie = new Movie(); 

}
blazor
  • 1 个回答
  • 16 Views
Martin Hope
user27339040
Asked: 2024-11-05 17:46:31 +0800 CST

如何使用 Blazor Bootstrap 创建新布局?

  • 5

我想要使​​用 Blazor Bootstrap 的 SideBar。NewLayout.razor:

@inherits LayoutComponentBase

<div class="bb-page">
    <Sidebar2 Href="/"
              IconName="IconName.BootstrapFill"
              Title="Blazor Bootstrap"
              BadgeText="v2.1.0"
              DataProvider="Sidebar2DataProvider" />

    <main>
        <div class="bb-top-row px-4 d-flex justify-content-end">
            <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
        </div>

        <article class="content px-4" style="position: relative;">
            <div class="py-2">
                @Body
            </div>
        </article>
    </main>
</div>

<style>
    .bb-page {
        display: flex;
        width: 100%;
        height: 100vh;
    }

    main {
        flex: 1;
        overflow: auto;
        min-width: 0;
    }
</style>

@code {

    IEnumerable<NavItem>? navItems;

    private async Task<Sidebar2DataProviderResult> Sidebar2DataProvider(Sidebar2DataProviderRequest request)
    {
        if (navItems is null)
            navItems = GetNavItems();

        return await Task.FromResult(request.ApplyTo(navItems));
    }

    private IEnumerable<NavItem> GetNavItems()
    {
        navItems = new List<NavItem>
        {
            new NavItem { Id = "1", Href = "/getting-started", IconName = IconName.HouseDoorFill, Text = "Getting Started"},

            new NavItem { Id = "2", IconName = IconName.LayoutSidebarInset, Text = "Content" },
            new NavItem { Id = "3", Href = "/icons", IconName = IconName.PersonSquare, Text = "Icons", ParentId="2"},

            new NavItem { Id = "4", IconName = IconName.ExclamationTriangleFill, Text = "Components" },
            new NavItem { Id = "5", Href = "/alerts", IconName = IconName.CheckCircleFill, Text = "Alerts", ParentId="4"},
            new NavItem { Id = "6", Href = "/breadcrumb", IconName = IconName.SegmentedNav, Text = "Breadcrumb", ParentId="4"},

            new NavItem { Id = "7", IconName = IconName.ListNested, Text = "Sidebar 2", ParentId="4"},
            new NavItem { Id = "701", Href = "/sidebar2", IconName = IconName.Dash, Text = "How to use", ParentId="7"},
            new NavItem { Id = "702", Href = "/sidebar2-examples", IconName = IconName.Dash, Text = "Examples", ParentId="7"},

            new NavItem { Id = "8", IconName = IconName.WindowPlus, Text = "Forms" },
            new NavItem { Id = "9", Href = "/autocomplete", IconName = IconName.InputCursorText, Text = "Auto Complete", ParentId="8"},
            new NavItem { Id = "10", Href = "/currency-input", IconName = IconName.CurrencyDollar, Text = "Currency Input", ParentId="8"},
            new NavItem { Id = "11", Href = "/number-input", IconName = IconName.InputCursor, Text = "Number Input", ParentId="8"},
            new NavItem { Id = "12", Href = "/switch", IconName = IconName.ToggleOn, Text = "Switch", ParentId="8"},
        };

        return navItems;
    }

}

我想将它用作客户端页面上的新布局。但它一直显示 3 点加载内容。( https://isstatic.askoverflow.dev/Jp3jQFK2.png )。有一个关于它的问题链接,但服务器项目中的 App.razor 对我来说不起作用。

我想将其用作客户端页面上的新布局。我发现此视频链接2最接近我想要的内容,但它在服务器端运行页面。

为了创建“@layout NewLayout”,布局必须在客户端,但即便如此,我也无法写入@rendermode InteractiveWebAssembly布局。出现以下错误:

“InvalidOperationException:无法将参数‘Body’传递给渲染模式为‘InteractiveWebAssemblyRenderMode’的组件‘NewLayout’。这是因为该参数属于委托类型‘Microsoft.AspNetCore.Components.RenderFragment’,它是任意代码,无法序列化。”

blazor
  • 1 个回答
  • 32 Views
Martin Hope
Manuel Rivera
Asked: 2024-11-01 02:29:14 +0800 CST

Blazor 服务器 - Fluent UI - 将焦点设置到 FluentDatePicker

  • 5

我可以将焦点设置到FluentTextField上:

  • 使用@ref:@ref=myFluentTextField

  • 将其声明为 FluentTextField:FluentTextField?nombreFluentTextField;

  • 设置焦点:

    protected override void OnAfterRender(bool firstRender) { nombreFluentTextField?.FocusAsync(); }

如果我尝试使用FluentDatePicker执行相同操作,我会在控制台中收到此错误:

ElementReference 尚未正确配置。

所以,问题是:如何将焦点从代码设置到FluentDatePicker?

非常感谢,再见……

blazor
  • 1 个回答
  • 24 Views
Martin Hope
thecodeiackiller
Asked: 2024-10-21 06:26:05 +0800 CST

如何维护 Blazor 表单中多个级联下拉菜单的单独状态?

  • 6

链接到 GitHub 以快速访问最小可重现示例(下面也提供了代码): https: //github.com/thecodeiackiller/cascadingSelectListProblem

  • #1)我有一份锻炼清单。
  • #2)我有 2 个枚举 (WorkoutType 和 ExerciseType),可以过滤锻炼列表。
  • #3)我有一个 EditForm,它允许用户: 选择 WorkoutType(LowerBody 或 UpperBody),它会过滤锻炼列表,并 选择 ExerciseType(Main、Secondary、Accessory),它会进一步过滤列表。

注意:对于那些不熟悉健身领域的人来说,在给定的锻炼中,您通常有一种锻炼类型(腿部锻炼、上身锻炼等),并且在该锻炼中,您有运动类型(主要/较重的运动、次要运动和辅助运动(锻炼小肌肉)。

预期按时间顺序排列的用户流量:

    1. 选择了 WorkoutType 并过滤了练习列表(我相信我的表格已经成功做到了这一点)。
    1. 对于 EditForm 中的第一行,用户选择一个 ExerciseType(主要、次要、附件)并且列表再次被过滤。
    1. 用户从现在经过两次筛选的列表中选择一项练习的名称。仍在第一行。
    1. 用户导航至第二行。
    1. 用户选择锻炼类型
    1. 用户从列表中选择新的练习名称(应根据第二行所选的练习类型进行过滤)。

问题:第二行的练习名称列表没有更新。练习名称列表与第一个练习相同,尽管练习类型不同,这应该会改变显示的练习。

我当前实现的AddWorkout.razor组件:

@using stateManagementMinimumReproducibleExample.Repositories
@using stateManagementMinimumReproducibleExample.Models
@page "/addworkout"
@rendermode InteractiveServer
@inject UserExerciseRepository userExerciseRepository

<EditForm Model="userExercise">
    <label for="workoutType"> Workout Type: </label>
    <InputSelect id="workoutType" @bind-Value="userExercise.WorkoutType" @bind-Value:after="GetExercisesByWorkoutType">
        @foreach (var type in Enum.GetValues(typeof(WorkoutType)))
        {
            <option value="@type">@type</option>
        }
    </InputSelect>

    @for (int i = 0; i < numberOfExercisesInWorkout; i++)
    {
        var j = i;
        if (j >= exerciseListForSelectedDay.Count)
        {
            exerciseListForSelectedDay.Add(new UserExercise());
        }

        <div>
            <label for="exerciseType"> Exercise Type: </label>
            <InputSelect id="exerciseType" @bind-Value="exerciseListForSelectedDay[j].ExerciseType" @bind-Value:after="GetExercisesByExerciseType">
                @foreach (var type in Enum.GetValues(typeof(ExerciseType)))
                {
                    <option value="@type">@type</option>
                }
            </InputSelect>

            <label for="exerciseName"> Exercise: </label>
            <InputSelect id="exerciseName" @bind-Value="exerciseListForSelectedDay[j].ExerciseId">
                @foreach (var exercise in listOfExerciseByExerciseType)
                {
                    <option value="@exercise.Id">@exercise.Name</option>
                }
            </InputSelect>
        </div>
    }
</EditForm>


@code {
    private int numberOfExercisesInWorkout = 2;

    private UserExercise userExercise = new();

    private List<UserExercise> exerciseListForSelectedDay = new();

    public List<Exercise> listOfExercisesByWorkoutType = new();

    public List<Exercise> listOfExerciseByExerciseType = new();

    public async Task GetExercisesByWorkoutType()
    {
            listOfExercisesByWorkoutType = await   userExerciseRepository.GetExercisesBasedOnWorkoutType(userExercise.WorkoutType);
            StateHasChanged();
    }

    public void GetExercisesByExerciseType()
    {
            listOfExerciseByExerciseType = userExerciseRepository.GetExercisesFromWorkoutListBasedOnExerciseType(listOfExercisesByWorkoutType, userExercise.ExerciseType);;
    }
}

我考虑过创建一个字典来存储锻炼中每项练习的练习列表的可能性。此外,我还考虑将 List 作为属性存储在我的 UserExercise 类中,然后将过滤后的练习列表添加到该属性中。我不确定我应该走哪条路,或者是否存在任何潜在的特定于 Blazor 的状态管理替代方案。

上面的代码应该能给你足够的信息来诊断问题。如果你需要直观的了解,以下是在分叉和克隆 GitHub 存储库后快速重现问题的步骤:

  • 启动应用程序
  • 导航至 /addworkout 端点
  • 选择锻炼类型(整个表格)
  • 选择锻炼类型(第一行)
  • 选择一项练习(第一行)
  • 选择锻炼类型(第二行)
  • 选择一项练习(第二行)

此时,您将看到,由于选择了与第一行不同的 ExerciseType,因此第二行的筛选列表尚未更新。我如何才能让第二行(及以后)的适当练习列表出现?谢谢。

blazor
  • 1 个回答
  • 33 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve