【问题标题】:Attaching page specific event handlers to an injected service in Blazor server将特定于页面的事件处理程序附加到 Blazor 服务器中的注入服务
【发布时间】:2021-06-28 17:40:09
【问题描述】:

我对 Blazor 服务器非常陌生,并且一般都在试验网页,并且无法弄清楚如何正确地将事件处理程序附加到应该根据当前页面触发不同操作的模式。我只是希望能够在提交时将页面信息作为电子邮件发送,但它最终会发送所有呈现的页面电子邮件,因为它认为每个事件都已触发。

我正在使用 Radzen 的 Blazor DialogService 并尝试遵循他们的 documentation 中的模式 - 像这样将方法附加到它

protected override void OnInitialized()
{
  DialogService.OnOpen += Open;

  DialogService.OnClose -= Close;
  DialogService.OnClose += Close;
}

private void Open(string Title, Type type, Dictionary<string, object> parameters, DialogOptions options)
{
}

private void Close(dynamic result)
{
  if (result == true)
  {
      JS.InvokeAsync<string>("DisableDialogSubmit", "nhDialogSubmit");
      SendEmail();
  }
}
async void Submit()
{
    await SubmitModal();
    DialogService.OnClose -= Close;
}

void OnInvalidSubmit()
{

}

async Task SubmitModal() => await DialogService.OpenAsync("Confirm Submission", (ds =>
    @<div style="top: 25%">
        <p Style="margin-bottom: 1rem">Submit Form?</p>
        <div class="row">
            <div class="col-md-12">
                <RadzenButton id="nhDialogSubmit" Text="Submit" Disabled="false" Click="() => ds.Close(true)" Style="margin-bottom: 10px; width: 150px" />
                <RadzenButton Text="Cancel" Click="() => ds.Close(false)" ButtonStyle="ButtonStyle.Secondary" Style="margin-bottom: 10px; width: 150px" />
            </div>
        </div>
    </div>),
new DialogOptions() { Width = "350px", Top = "35%", Left = "25%" });

这段代码在 SendEmail() 中以不同的逻辑复制粘贴在每个页面上一开始就完全错误地使用它。我希望按范围注入服务可以让我做到这一点;将它创建为瞬态完成我的实现吗?我很难找到合适的东西来搜索以管理单页应用程序中任何服务上的事件,因此非常感谢任何提示或指针!

【问题讨论】:

    标签: asp.net-core event-handling blazor single-page-application blazor-server-side


    【解决方案1】:

    您指向的文档使用@implements IDisposableDispose(),这更有意义。

    我认为完整的事件处理应该看起来像他们的,没有其他任何地方的 +=-=

    @implements IDisposable
    
    ...
    
    @code {
    
        protected override void OnInitialized()
        {
            DialogService.OnOpen += Open;
            DialogService.OnClose += Close;
        }
    
        public void Dispose()
        {
            // The DialogService is a singleton so it is advisable to unsubscribe.
            DialogService.OnOpen -= Open;
            DialogService.OnClose -= Close;
        }
    
        ...    
    }
    

    另外,您不应该需要 JS 并将 Submit() 方法设为 async Task,而不是 async void

    【讨论】:

    • 现在我觉得很傻,非常感谢!我几乎可以肯定这个库的旧版本没有实现 IDisposable 或 Dispose(),但我应该回过头来看它。现在它工作得更干净了!
    • 关于 JS 的使用 - 我曾尝试使用 Components disabled 标志和 StateHasChanged()/Task.Delay() 制作提交任务并禁用按钮,但它仍然无法正常工作。我想我在正确理解 asp.net 核心之前搞砸了建立一个库。确认这应该是可能的,但正确的解决方案非常有帮助。再次感谢您解决此问题!
    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    相关资源
    最近更新 更多