I'm attempting to pass an object to a javascript function via jint and return a value. But it doesn't seem to work. Here is what I have tried so far -
Error -
Jint.Runtime.JavaScriptException: 'obj is undefined'
Using the following code -
var carObj = JsonSerializer.Serialize(car);
var engine = new Jint.Engine();
engine.SetValue("obj", carObj);
var value = engine
.Execute("const result = (function car(obj) { const type = obj.Type; return type;})()")
.GetValue("result");
As shown in the docs, you should pass your POCO car
directly to Jint.Engine
rather than trying to serialize it to JSON. Jint will use reflection to access its members.
Thus your code can be rewritten as follows:
var value = new Jint.Engine() // Create the Jint engine
.Execute("function car(obj) { const type = obj.Type; return type;}") // Define a function car() that accesses the Type field of the incoming obj and returns it.
.Invoke("car", car); // Invoke the car() function on the car POCO, and return its result.
Or equivalently as:
var value = new Jint.Engine()
.SetValue("obj", car) // Define a "global" variable "obj"
.Execute("const result = (function car(obj) { const type = obj.Type; return type;})(obj)") // Define the car() function, call it with "obj", and set the value in "result"
.GetValue("result"); // Get the evaluated value of "result"
Or
var value = new Jint.Engine() // Create the Jint engine
.SetValue("obj", car) // Define a "global" variable "obj"
.Execute("function car(obj) { const type = obj.Type; return type;}; car(obj);") // Define the car() function, and call it with "obj".
.GetCompletionValue(); // Get the last evaluated statement completion value
Here I am assuming that car
is a POCO that has a string property Type
, e.g.
var car = new
{
Type = "studebaker convertible",
};
Demo fiddle here.