Hi Ahmed, just like we know in Blazor we can't write and execute js code direct, the same as Jquery code. According to your code snippet, I recommend you referring to this document to inject your js code, or this section for more details.
I also had a test in my side which is based on a newly created blazor server(.net 7) app. I import jquery in Pages -> _Host.cshtml
...
<script src="_framework/blazor.server.js"></script>
<script src="~/js/jquery-3.6.4.js"></script>
</body>
</html>
I created a file Counter.razor.js
:
export function showPrompt(message) {
return prompt(message, 'Type anything here');
}
export function alertTitle() {
var title = $("#myTitle").val();
alert("the title is :" + title);
}
export function init() {
$("#hideBtn").click(function () {
alert(1);
$(this).hide();
});
}
My Counter.razor
@page "/counter"
@inject IJSRuntime JS
@implements IAsyncDisposable
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<p>
<button @onclick="TriggerPrompt">Trigger browser window prompt</button>
</p>
<div>
<laber>please enter the title</laber>
<input id="myTitle" type="text" />
<input type="button" value="alert title" @onclick="myAlert" />
</div>
<div>
<input type="button" value="click to hide" id="hideBtn" />
</div>
<p>@result</p>
@code {
private int currentCount = 0;
private IJSObjectReference? module;
private string? result;
private void IncrementCount()
{
currentCount++;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
module = await JS.InvokeAsync<IJSObjectReference>("import", "./Pages/Counter.razor.js");
await module.InvokeAsync<string>("init");
}
}
private async Task TriggerPrompt()
{
result = await Prompt("Provide some text");
}
private async Task myAlert()
{
await module.InvokeAsync<string>("alertTitle");
}
public async ValueTask<string?> Prompt(string message) =>
module is not null ?
await module.InvokeAsync<string>("showPrompt", message) : null;
async ValueTask IAsyncDisposable.DisposeAsync()
{
if (module is not null)
{
await module.DisposeAsync();
}
}
}
Test result:
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
TinyWang