此功效无法百分百通过 C# 代码来实现,需要与 JS 举行交互。
先编写 JS:

s
window.clipboardCopy = {
    copyText: function (text) {
        navigator.clipboard.writeText(text).then(function () {
            alert("Copied to clipboard!");
        })
            .catch(function (error) {
                alert(error);
            });
    }
};

该 JS 放置的位置,可以写在 Js 文件中,在 Index.html 中应用,也可以直接写在 Index.html 中。
然后在 Razor 组件中注入 JSRuntime,并调用该 JS:

r
@page "/counter"
@inject IJSRuntime JsRuntime
<h1>GUID 天生器</h1>
<div class="row">
    <div class="col-2">
        <input class="form-control" type="text" value="@_guidValue" />
    </div>
    <div class="col-10">
        <button class="btn btn-primary" @onclick="GenerateGuid">生 成</button>
        <button class="btn btn-danger" @onclick="CopyTextToClipboard">复制到剪贴板</button>
    </div>
</div>
@code {
    private Guid? _guidValue;
    private void GenerateGuid()
    {
        _guidValue = Guid.NewGuid();
    }
    private async Task CopyTextToClipboard()
    {
        await JsRuntime.InvokeVoidAsync("clipboardCopy.copyText", _guidValue);
    }
}
更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Roc 微信支付

微信支付

Roc 支付宝

支付宝