利用noesis.Javascript开源组件.Net中执行javascript脚本

界面如下:

利用noesis.Javascript开源组件.Net中执行javascript脚本

然后,click filter button后的UI:

利用noesis.Javascript开源组件.Net中执行javascript脚本

看,筛选出来了,代码如下(js能调C#写的UserInfo类的各个属性)

复制代码 代码如下:


public class UserInfo
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public override string ToString()
        {
            return string.Format("{0}, {1}: {2}", FirstName, LastName, Age);
        }
    }

private void btnSearch_Click(object sender, EventArgs e)
        {
            List<UserInfo> users = FilterUsers(txtFilter.Text.Trim());
            lstUsers.DataSource = users;
        }

private List<UserInfo> FilterUsers(string jsFilter)
        {
            List<UserInfo> results = new List<UserInfo>();
            if (jsFilter.Trim().Length == 0)
                return this.users;

try
            {
                using (JavascriptContext context = new JavascriptContext())
                {
                    foreach (UserInfo user in this.users)
                    {
                        context.SetParameter("user", user);
                        context.SetParameter("isInclude", false);
                        string js = string.Format(@"
                                                if({0})
                                                    isInclude=true;
                                                else
                                                    isInclude=false;", jsFilter);
                        context.Run(js);
                        bool isInclude = (bool)context.GetParameter("isInclude");
                        if (isInclude)
                            results.Add(user);
                    }
                }
            }
            catch
            {
                txtFilter.Focus();
                txtFilter.SelectAll();
                return this.users;
            }

return results;
        }

我们来看看效率:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgyfj.html