You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中如何将按钮ID与Class传递至模态弹窗实现动态数据展示

实现按钮参数传递给模态弹窗展示动态数据

当然可以将按钮的ID和Class作为参数传递给模态弹窗,从而实现标题和单位的动态变化。以下是具体的修改步骤:

1. 修改Modal.razor组件

在Modal组件中添加接收参数的属性,更新Open方法以接收参数,并修改渲染部分使用动态值:

<h5 class="modal-title">@ModalTitle</h5>

<div class="modal-body">
        <label for="Min">Enter Min</label>
        <input @bind="min" type="text" id="Min" name="Min">[@MeasurementUnit]<br>
        <label for="Max">Enter Max:</label>
        <input @bind="max" type="text" id="Max" name="Max">[@MeasurementUnit]<br>
</div>
<div class="modal-footer">
        <button type="button" class="btn btn-primary" @onclick="() => Done()">Done</button>            
</div>


@code {
private string min;
private string max;
public string ModalTitle { get; set; }
public string MeasurementUnit { get; set; }

public Guid Guid = Guid.NewGuid();
public string ModalDisplay = "none;";
public string ModalClass = "";
public bool ShowBackdrop { get; set; }

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


public void Open(string title, string unit)
{
    ModalTitle = title;
    MeasurementUnit = unit;
    ModalDisplay = "block;";
    ModalClass = "Show";
    ShowBackdrop = true;
    StateHasChanged();
}

public void Close()
{
    ModalDisplay = "none";
    ModalClass = "";
    ShowBackdrop = false;
    StateHasChanged();
}

public async Task Done()
{
    await InvokeAsync(() => OnDoneCallback1.InvokeAsync(min));
    await InvokeAsync(() => OnDoneCallback2.InvokeAsync(max));
    Close();
}
}

2. 修改Navbar.razor组件

更新按钮的点击事件,传递对应按钮的Class作为标题、ID作为单位,并确保Modal组件正确引用:

<li><button class="firstButtonDialog" id="mm" @onclick="() => _modal.Open("firstButtonDialog", "mm")">mm</button></li>
<li><button class="secondButtonDialog" id="cm" @onclick="() => _modal.Open("secondButtonDialog", "cm")">cm</button></li>
<li><button class="thirdButtonDialog" id="meter" @onclick="() => _modal.Open("thirdButtonDialog", "meter")">meter</button></li>

<Modal @ref="_modal" OnDoneCallback1="OnModalMin" OnDoneCallback2="OnModalMax" />

@code {
private Modal _modal { get; set; }
public string _min { get; set; }
public string _max { get; set; }

private void OnModalMin(string min)
{
    _min = min;  
}

private void OnModalMax(string max)
{
    _max = max;
}
}

说明

  • 点击不同按钮时,按钮的Class值会传递给Modal的ModalTitle属性,ID值传递给MeasurementUnit属性
  • Modal组件会根据接收到的参数动态渲染标题和单位
  • 补充了Modal中缺失的ShowBackdrop属性,并在Done方法中添加关闭弹窗逻辑,提升交互体验

内容的提问来源于stack exchange,提问作者Tar270

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:01:04