我想将javascript对象直接传递给Blazor中的c#方法。如果我调用GetModel方法,它返回的是我传递的同一对象,而不是更新后的对象。我遵循了以下流程。
JavaScript Object
export interface ITestItem {
data: string;
moreData: string;
}
C# Object
public class ITestItem
{
public string data { get; set; }
public string moreData { get; set; }
}
Method in C#:
public static ITestItem GetModel(ITestItem item)
{
item.moreData = "Get Model Working Fine";
return item;
}
Calling C# method from JavaScript
public getModel() {
const getModelFunc = Module.mono_bind_static_method("
[Report]Epicor.MetaFx.Wasm.Dynamic.RunClass:GetModel");
const item: ITestItem = { data: 'Test', moreData: 'checking Get Model' };
const output = getModelFunc(item);
console.log(output);
}
看起来这是Blazor中的TypeScript
项目。
我用ASP.NET Core 3.1尝试了这个解决方案,它很有效。
假设您的项目(组件(名称为CICalc
1.在wwwroot文件夹中添加exampleJsInterop.ts文件
namespace JSInteropWithTypeScript {
export interface ITestItem {
data: string;
moreData: string;
}
class ExampleJsFunctions {
public getModel(): void {
const item: ITestItem = { data: 'Test', moreData: 'checking Get Model' };
(window as any).DotNet.invokeMethodAsync('CICalc', 'GetModel', item)
.then(data => {
console.log(data);
});
}
}
export function Load(): void {
window['exampleJsFunctions'] = new ExampleJsFunctions();
}
}
JSInteropWithTypeScript.Load();
2.在.csproj 中添加内部版本Microsoft.TypeScript.MBuild包引用和编译条件
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<RazorLangVersion>3.0</RazorLangVersion>
<TypeScriptToolsVersion>3.2</TypeScriptToolsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="3.2.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="3.9.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="System.Net.Http.Json" Version="3.2.0" />
</ItemGroup>
<ItemGroup>
<TypeScriptCompile Include="wwwroot/exampleJsInterop.ts" />
</ItemGroup>
</Project>
3.在index.html中导入exampleJsInterop.js。重要的是它是.js.ts,因为dotnet会将ts编译到js中。
<script src="exampleJsInterop.js"></script>
4.在您的页面中,添加按钮以触发getModel函数,并添加静态getModelC#函数
<button type="button" class="btn btn-primary"
onclick="exampleJsFunctions.getModel()">
Trigger .NET static method
</button>
@code {
[JSInvokable]
public static Task<ITestItem> GetModel(ITestItem item)
{
item.moreData = "Get Model Working Fine";
return Task.FromResult(item);
}
public class ITestItem
{
public string data { get; set; }
public string moreData { get; set; }
}
}
5.最后,当你点击按钮时,js会从C#中得到结果。
参考:Blazor 中JSInterop的TypeScript入门