[英]Blazor pass a javascript object as an argument for IJSRuntime
I want to pass a javascript
object that is already existed in a javascript
file as a parameter to InvokeVoidAsync
method:我想将
javascript
文件中已经存在的javascript
作为参数传递给InvokeVoidAsync
方法:
myJs.js : myJs.js :
var myObject= {a:1,b:2};
MyComponent.razor : MyComponent.razor :
@inject IJSRuntime js
@code {
private async Task MyMethod()
{
await js.InvokeVoidAsync("someJsFunction", /*how to add myObject here? */);
}
}
How to pass myObject
to the someJsFunction
function?如何将
myObject
传递给someJsFunction
function? ( Note that the function may also should accept c# objects too ) (请注意,function 也应该接受 c# 对象)
I finally found the trick, simply use the eval
function:我终于找到了诀窍,只需使用
eval
function:
private async Task MyMethod()
{
object data = await js.InvokeAsync<Person>("eval","myObject");
await js.InvokeVoidAsync("someJsFunction", data );
}
You could define a new JS function您可以定义一个新的 JS function
someJsFunctionWithObj(){
someJsFunction(myObject);
}
Then call that instead...然后改为调用...
await js.InvokeVoidAsync("someJsFunctionWithObj");
Or create a JS function that returns the object -> call that from C# to get it -> then pass it back, but that seems quite convoluted.或者创建一个返回 object 的 JS function -> 从 C# 调用它来获取它 -> 然后将其传回,但这似乎很复杂。
It sounds like probably you should rethink your design really... Maybe if you explained why you are actually trying to do this we can suggest better idea?听起来您可能真的应该重新考虑您的设计......也许如果您解释了为什么您实际上要这样做,我们可以提出更好的想法?
in the example below, "someJsFunction" accepts an object of type Person:在下面的示例中,“someJsFunction”接受 Person 类型的 object:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
in my javascript file在我的 javascript 文件中
var myObject = { name: "Pat", age: 38 }; //a person
//this function provides access to myObject
window.getMyObject = () =>
{
return myObject;
};
window.someJsFunction = (person) =>
{
console.log(person);
}
In the component:在组件中:
@page "/"
@inject IJSRuntime js
<div>
<button @onclick="MyMethod" >Click</button>
</div>
@code{
Person Person;
protected async override Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
//retrieve myOject and assign to the field Person
Person = await js.InvokeAsync<Person>("getMyObject");
}
}
private async Task MyMethod()
{
if(Person != null)
//pass Person to someJsFunction
await js.InvokeVoidAsync("someJsFunction", Person);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.