这里有谁有使用Javascript.Net的经验吗?
我使用JavaScript.Net将javascript嵌入到c#中。
我有一个简单的任务来检查我给定的变量是否是一个有效的数组。通过将变量附加到脚本中,我设法获得了正确的答案。
此方法工作并返回true
JavascriptContext context = new JavascriptContext();
public static string IsValidArray(string vari , JavascriptContext context)
{
object isValid = context.Run(@"
function check(){ var arr = " + vari + ";if(arr.constructor == Array){return true; }else {return false;}} check();");
return (string)isValid;
}它工作得很好。但是当我尝试将这个变量作为函数的参数传递时,它返回false。代码如下:
JavascriptContext context = new JavascriptContext();
string array = "['hello','hello2']";
context.SetParameter("arr", array);
string isValid = IsValidArray(context);
public static string IsValidArray(JavascriptContext context)
{
object isValid = context.Run("function check(vari){return (vari.constructor == Array);} check(arr);");
return (string)isValid;
}如何使用参数来实现?
发布于 2016-03-17 19:31:44
我会详细说明我的评论。
我认为您的问题在于您传递的是数组的字符串表示,而不是数组。你可以试试context.SetParameter("arr",new[] {"hello",“hello2”);
如果你有一个字符串,并且想把它转换成一个对象,我建议你使用Json.NET,这是非常棒的。搜索有关如何安装它的教程。然后,您可以简单地执行以下操作:
string json = "['hello','hello2']";
List<String> array = Newtonsoft.Json.JsonConvert.DeserializeObject<List<String>>(json);另一种方法,但我对JavaScript.Net的了解还不够多,无法告诉你哪种方法更可取,那就是按原样读取字符串,然后将它传递给JavaScript,知道它只是一个字符串,然后在JavaScript中调用JSON.parse(theString),以便将其解释为数组、对象或其他任何形式。
https://stackoverflow.com/questions/36042110
复制相似问题