ใน Blazor การใช้คำสั่ง Javascript มันช่างยากลำบาก แค่จะ console.log ก็ยากแล้ว เพราะต้อง Inject IJSRuntime ก่อน แล้วค่อยใช้คำสั่ง InvokeVoidAsync(“console.log”, “พ่นออกมาสิโว้ย”);
แล้วต้องทำงี้ทุกหน้า โครตยากกกกกกกก ทำให้เราคิดว่า เอ้อ ทำไฟล์ Service ตัวนึงไว้ใช้ก็ไม่เลว
ไฟล์ JavascriptService.cs
// Services/JavascriptService.cs
using Microsoft.JSInterop;
namespace YourProjectName.Services;
public class JavascriptService
{
private readonly IJSRuntime _js;
public JavascriptService(IJSRuntime js)
{
_js = js;
}
public async Task<bool> Confirm(string message = "")
{
string textAlert = !string.IsNullOrWhiteSpace(message) ? message : "ยืนยันการทำรายการ?";
return await _js.InvokeAsync<bool>("confirm", textAlert);
}
public async Task ConsoleLog(string message)
{
await _js.InvokeVoidAsync("console.log", message);
}
}
แก้ไฟล์ Program.cs
// Program.cs builder.Services.AddScoped<JavascriptService>(); // บริการเกี่ยวกับ Javascript
วิธีใช้ใน Blazor
สมมติเป็นกรณีกดปุ่มแล้วออกจากระบบละกัน
// Components/Layout/MainLayout.cs
@inject JavascriptService JavascriptService
<button @onclick="Logout">Logout</button>
@code {
private async Task Logout()
{
bool result = await JavascriptService.Confirm("ยืนยันการออกจากระบบ?");
if (result) // ถ้าผู้ใช้คลิก 'OK'
{
await JavascriptService.ConsoleLog("ผู้ใช้คลิกออกจากระบบ");
}
}
}
