在sqldependency更改后调用clientside函数

时间:2013-10-23 14:20:27

标签: c# javascript asp.net postback sqldependency

我正在使用SqlDependency来监视特定db表的更改。 我需要在触发更改事件后调用javascript事件!任何的想法 ? 这段代码在我的asp.net页面代码后面

    public void StartTasksMonitor()
    {
        var con = new SqlConnection { ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString };

            if (con.State== System.Data.ConnectionState.Closed)
            {
                con.Open();
            }
            var cmd = new SqlCommand { CommandText = @"SELECT Id
      ,AssignedBy
      ,DateAssigned
      ,AssignedTo
      ,Title
      ,Description
      ,Completed
      ,DateDue
      ,Deleted
      ,DateDeleted
  FROM dbo.Tasks", Connection = con, Notification = null };

            SqlDependency dependency = new SqlDependency(cmd);
            SqlDataReader reader = cmd.ExecuteReader();
            con.Close();
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);


    }

    void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            // Have to remove this as it only work's once
            SqlDependency sqlDep = sender as SqlDependency;
            sqlDep.OnChange -= dependency_OnChange;

            // Resetup Dependecy
            StartTasksMonitor();
            string clientFunc = @"alert('test')";

            ScriptManager.RegisterStartupScript(this, GetType(), "alert", clientFunc , true);


        }

    }

RegisterStartupScript仅在发生回发时才有效。这里没有回发。整个事情的主要目的是避免回发:)

1 个答案:

答案 0 :(得分:0)

使用SignalR解决了它:) SignalR + SQLDependency是一个踢屁股配方:) 快乐编码