【发布时间】:2020-03-31 15:26:09
【问题描述】:
(#)首发
我正在使用 JSInterop 和 Blazor/RazorPages 在单击表上的项目时调用方法。互操作规范只允许使用静态方法。好吧,从技术上讲,也可以使用实例方法,但其文档确实令人困惑。我几乎可以肯定,如果没有 Blazor '@onclick' tag-helper,实例方法调用将无法工作——我无法在本示例中使用它。
这是有效的:
public class Dashboard : PageModel
private readonly DeviceService _deviceService;
public Dashboard (DeviceService deviceService)
{
_deviceService = deviceService;
}
//I want to use the above instance of deviceService, for a JSInvokable method
[JSInvokable]
public static async Task<List<string>> DeviceDetails(string deviceName)
{
List < string > details = new List<string>();
Uri location = new Uri("http://superapi.com/api/devices");
HttpClient client = new HttpClient();
client.BaseAddress = location;
DeviceService dev = new DeviceService(client);
Device details = await dev.GetDeviceByName(deviceName);
return details;
}
//This <script> is what the client gets in their browser when they visit the page.
function () {
var table = $('#<TableName>').DataTable();
var d = table.row(this).data();
DotNet.invokeMethodAsync("<namespace>", "DeviceDetails", d[0])
.then(data => {
document.getElementById("Property1").innerHTML = data[0];
document.getElementById("Property2").innerHTML = data[1];
document.getElementById("Property3").innerHTML = data[2];
document.getElementById("Property4").innerHTML = data[3];
document.getElementById("Property5").innerHTML = data[4];
});
});
invokeMethodAsync 的 MS 文档声明它仅适用于静态方法,这些方法不允许我访问我在 PageModel 中声明的 DeviceService 实例。它迫使我用“新”的一切创建一个相当丑陋的新实例。
我认为解决方案可能涉及使用接口或依赖注入,有人有建议吗?
【问题讨论】:
-
这是对您问题的回答吗? stackoverflow.com/questions/59134029/…
-
@agua from mars 不是真的,我不是从 .razor 页面调用。这是一个常规的 .cshtml
-
贴出代码,没有上下文我们帮不了你
-
我已经添加了调用 JSInvokable 方法的 JS 脚本。这是在使用 blazor 服务器的 .cshtml 页面上。让我知道这是否是您在“上下文”方面正在寻找的内容。
-
我的意思是,在所有上下文中,我们无法猜测它是从 blazor 应用程序外部的 cshtml 调用的,这是您尝试做的吗?
标签: javascript c# razor static-methods blazor