我的 Blazor .NET Core 5.x“@inject IJSRuntime JS”语句从 Visual Studio 2019 收到 CS0246 错误

问题描述

我正在使用 Blazor 和 .NET Core 5.x,我正在尝试让一些 JavaScript 工作,但依赖注入语句不起作用。这是我所拥有的:

_Host.cshtml:

@page "/"
@namespace MyAwesomeApp.Pages
@inject IJSRuntime JS
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
    <head>
        <Meta charset="utf-8" />
        <Meta name="viewport" content="width=device-width,initial-scale=1.0" />
        <title>My Awesome App</title>
        <base href="~/" />
        <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
        <link rel="stylesheet" href="css/site.css" />
        <script type="text/javascript" src="~/JavaScript.js"></script>
    </head>
    <body onload="start();">
        <component type="typeof(App)" render-mode="ServerPrerendered" />
        .
        .
        .
    </body>
</html>

MainLayout.razor:

@inherits LayoutComponentBase

<div>
    <div>
        <div>
            @Body
        </div>
    </div>
</div>

Index.razor:

@page "/"

<div class="text-center">
    <div id="search_container">
        <form id="" method="" action="">
            <img src="/images/magnifying_glass.svg" type="image/svg+xml" /><input id="search_field" type="text" /><span id="clear_search">&#xd7;</span>
        </form>
    </div>
</div>

JavaScript.js:

var search_field;
var clear_search_button;

function start() {
    search_field = document.getElementById('search_field');
    clear_search_button = document.getElementById('clear_search');

    search_field.focus();

    clear_search_button.addEventListener('click',function () {
        search_field.value = null;
        search_field.focus();
    });
}

但是,Visual Studio 2019 在 @inject 语句中给了我这个错误,特别是在 IJSRuntime 词下:

Error   CS0246  The type or namespace name 'IJSRuntime' Could not be found (are you missing a using directive or an assembly reference?)

解决方法

对于您的问题,您需要在 _Host.cshtml 中添加命名空间:

@using Microsoft.JSInterop;
@inject IJSRuntime JS

但实际上,_Host.cshtml是用来添加js文件的,需要使用JSRuntime来调用razor组件中的js函数:

@page "/"

@inject IJSRuntime JS

<div class="text-center">
    <div id="search_container">
        <form id="" method="" action="">
            <img src="/images/magnifying_glass.svg" type="image/svg+xml" /><input id="search_field" type="text" /><span id="clear_search">&#xd7;</span>
        </form>
    </div>
</div>

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync(
                "start");
        }
    }
}