我正在尝试使用 SignalR 进行实时网页更新,这是我第一次尝试。我的ajax命令正在调用我的服务器代码。但它不会从服务器端返回任何内容。
这是脚本
<script>
$(function () {
//Proxy created on the fly
var job = $.connection.myHub;
//Declare a function on the hub so the server can invoke it
job.client.displaystatus = function () {
getData();
};
//Start the connection
$.connection.hub.start();
getData();
});
function getData() {
//alert('ok');
var $tb1 = $('#tb1');
$.ajax({
url: 'Default.aspx/GetData',
contentType: "application/json; charset-utf-8",
dataType: "json",
type: "POST",
success: function (data) {
alert('Success:' + data);
},
error:function(){
alert('Failed');
}
});
}
</script>
Default.cs代码
[WebMethod]
public static IEnumerable<Product> GetData()
{
string cs = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
//Make sure the command object does not already have
using (SqlCommand cmd = new SqlCommand("SELECT [Id],[Name],[PricDecimal],[QuantDecimal]FROM [TestDatabase].[dbo].[Product]"))
{
cmd.Connection = con;
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (con.State == ConnectionState.Closed)
con.Open();
using (var reader = cmd.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new Product()
{
id = x.GetInt32(0),
Name = x.GetString(1),
PricDecimal = x.GetDecimal(2),
QuantDecimal = x.GetDecimal(3)
}).ToList();
}
}
}
private static void dependency_OnChange(object sender,SqlNotificationEventArgs e)
{
MyHub.show();
}
Default.cs文件中的产品类
public class Product
{
public int id { get; set; }
public string Name { get; set; }
public decimal PricDecimal { get; set; }
public decimal QuantDecimal { get; set; }
}
MyHub.cs文件
public class MyHub : Hub
{
public static void show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
Startup.cs文件
[assembly: OwinStartup(typeof(Startup))]
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
//string cs = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
//System.Data.SqlClient.SqlDependency.Start(cs);
}
}
错误消息
ExceptionType : “System.InvalidOperationException”
信息 : “在不提供选项值的情况下使用SqlDependency时,必须在执行添加到SqlDependency实例的命令之前调用SqlDependency.Start()。”
答案 0 :(得分:1)
我认为为时已晚,但您需要在新的SqlDependency之前编写此行:
SqlDependency.Start("connection string");