您好,我正在尝试从js
的{{1}}文件中调用方法。
我的文件结构是这样的:
Blazor
我一直收到以下错误:
-root
-JSInterop.cs
-js(folder)
-meth.js (file containing the js method)
**调用js的CS类**
Could not find 'methods' in 'window'.
Js文件
public class JSInterop {
public static async Task<string> ChangeText() {
try {
var data = await JSRuntime.Current.InvokeAsync<string>("./js/meth/methods.print","mymessage");
Console.WriteLine($"ReturnedFromJS:{data}");
return data;
} catch (Exception ex) {
return ex.Message;
}
}
}
我尝试过只将方法和属性都放在function print(message){
return "fromJs"+message;
}
window.methods = {
print: function (message) {
return "from js" + message;
}
}
中。在第一种情况下,我不确定如何从js文件中引用方法。
window
无济于事(在第二种情况下)
Index.html
"[path to file]/[containingfile]/[methodname]" ?
or i have also tried "[path to file] / window.[methodname]"
答案 0 :(得分:2)
下面是编写cookie的端到端示例。
步骤1-添加MatButton
,并将其onClick
属性设置为delegate
。
<MatButton TrailingIcon="favorite" @onclick="@(async () => await AddItemtoShoppingCart(@item))" Label="add"></MatButton>
第2步
@code{
public async Task AddItemtoShoppingCart(FoodItem selectedItem)
{
var test = await JSRuntime.InvokeAsync<object>("blazorExtensions.WriteCookie", "cookieName", "cookieValue", "cookieExpiryDate");
}
}
第3步-在_Host.cshtml
的javasceipt中添加
<script>
window.blazorExtensions = {
WriteCookie: function (name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
}
</script>
答案 1 :(得分:1)
// Try this:
// Don't call your class JSInterop
public class MyJSInterop {
public static async Task<string> ChangeText() {
try {
var data = await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
Console.WriteLine($"ReturnedFromJS:{data}");
return data;
} catch (Exception ex) {
return ex.Message;
}
}
}
// Js file
window.methods = {
print: function (message) {
return "from js" + message;
}
};
答案 2 :(得分:1)
JSRuntime.Current.InvokeAsync将相对于全局 window 范围的js函数标识符作为其第一个参数。因此,在您的js文件中,您可能有:
window.methods = {
print: function (message) {
return "from js" + message
}
将您的js文件添加到index.html
<script src="css/bootstrap/bootstrap-native.min.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
<script src="js/meth.js"></script>
并按照以下说明从.Net调用
await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");