Asp.net mvc 5 信号器数据库更新通知

Asp.net mvc 5 信号器数据库更新通知,asp.net-mvc-5,signalr,jquery-ajaxq,Asp.net Mvc 5,Signalr,Jquery Ajaxq,我正在用asp.NETMVC5开发一个应用程序。在这个项目中,我使用signalR实时显示更新的数据。这意味着,当任何数据发生变化时,它们都将加载到应用程序UI中。但不幸的是,除非我刷新页面,否则它不会自动加载 下面是我的代码: Hub : [HubName("statusLog")] public class StatusLogHub : Hub { [HubMethodName("sendExportStatus")] public void SendExportStat

我正在用asp.NETMVC5开发一个应用程序。在这个项目中,我使用signalR实时显示更新的数据。这意味着,当任何数据发生变化时,它们都将加载到应用程序UI中。但不幸的是,除非我刷新页面,否则它不会自动加载

下面是我的代码:

Hub :

[HubName("statusLog")]
public class StatusLogHub : Hub
{

    [HubMethodName("sendExportStatus")]
    public void SendExportStatus()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatusLogHub>();
        Clients.All.updateStatus();
    }
}

Repository :

public class EmailStatusLogRepository
{

    readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public IEnumerable<EmailStatusLog> GetExportStatus()
    {
        var messages = new List<EmailStatusLog>();
        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(@"SELECT * FROM dbo.EmailStatusLogs WHERE ExportStatus = 1 AND CAST(CONVERT(VARCHAR,Date,101) AS DATETIME)=CAST(CONVERT(VARCHAR,'" + DateTime.Now.Date.ToString("MM/dd/yyyy") + @"',101) AS DATETIME)", connection))
            {
                command.Notification = null;

                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                if (connection.State == ConnectionState.Closed)
                    connection.Open();

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    messages.Add(item: new EmailStatusLog { Id = (int)reader["Id"], Investor_Code = (string)reader["Investor_Code"], EmailId = reader["EmailId"] != DBNull.Value ? (string)reader["EmailId"] : "", Date = (string)reader["Date"], ReportName = (string)reader["ReportName"], ExportStatus = (bool)reader["ExportStatus"], EmailSendStatus = (bool)reader["EmailSendStatus"], IsActive = (bool)reader["IsActive"] });
                }
            }

        }
        return messages;
    }
    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            StatusLogHub statusLogHub = new StatusLogHub();
            statusLogHub.SendExportStatus();
        }
    }

}

//Code from where I am updating DB:

public void ExportStatus()
    {
        List<EmailStatusLog> lstEmailStatusLog = new List<EmailStatusLog>();
        EmailStatusLog objEmailStatusLog = new EmailStatusLog();
        foreach (var emailItem in lstEmailReceipent)
        {
            EMailDBContext _ctx = new EMailDBContext();
            objEmailStatusLog.EmailId = emailItem.stEmailAdd;
            objEmailStatusLog.Investor_Code = emailItem.stInvestor_code;
            objEmailStatusLog.Date = DateTime.Now.ToString("MM/dd/yyyy");
            objEmailStatusLog.ReportName = reportName;
            objEmailStatusLog.ExportStatus = IsSuccess;
            objEmailStatusLog.EmailSendStatus = false;
            objEmailStatusLog.IsActive = true;
            _ctx.emailStatusLogs.Add(objEmailStatusLog);
            _ctx.SaveChanges();
            //StatusLogHub objStatusLogHub = new StatusLogHub();
            //objStatusLogHub.SendExportStatus();

        }
    }

Controller :

public ActionResult GetExportStatus()
    {
        EmailStatusLogRepository objEmailStatusRepository = new EmailStatusLogRepository();
        return PartialView("_exportedReportList", objEmailStatusRepository.GetExportStatus());
    }

Javascript: 

<script type="text/javascript" language="javascript">
//==================signalR
$(function () {
    var hub = $.connection.statusLog;
    hub.client.updateStatus = function () {
        getExportStatus()
    };
    $.connection.hub.start().done(function () {
        alert("connection started");
        // hub.server.sendExportStatus($('').val());
        getExportStatus();
    }).fail(function (e) {
        alert(e);
    });
});


function getExportStatus() {
    var tbl = $('#statusTable');
    $.ajax({
        url: '@Url.Action("GetExportStatus")',
        contentType: 'application/html ; charset:utf-8',
        type: 'GET',
        dataType: 'html'
    }).success(function (result) {
        tbl.empty().append(result);
    }).error(function () {

    });
}
Hub:
[HubName(“状态日志”)]
公共类StatusLogHub:Hub
{
[HubMethodName(“sendExportStatus”)]
公共无效SendExportStatus()
{
IHubContext context=GlobalHost.ConnectionManager.GetHubContext();
Clients.All.updateStatus();
}
}
存储库:
公共类EmailStatusLogRepository
{
只读字符串_connString=ConfigurationManager.ConnectionString[“DefaultConnection”]。ConnectionString;
公共IEnumerable GetExportStatus()
{
var messages=新列表();
使用(var连接=新的SqlConnection(_connString))
{
connection.Open();
使用(var command=new SqlCommand(@“从dbo.EmailStatusLogs中选择*,其中ExportStatus=1并转换(将(VARCHAR,Date,101)转换为DATETIME)=转换(将(VARCHAR,“+DATETIME.Now.Date.ToString”(“MM/dd/yyyy”)+@“,101)转换为DATETIME)”,连接)
{
command.Notification=null;
var-dependency=newsqldependency(命令);
dependency.OnChange+=新的OnChangeEventHandler(dependency\u OnChange);
if(connection.State==ConnectionState.Closed)
connection.Open();
var reader=command.ExecuteReader();
while(reader.Read())
{
消息。添加(项目:新EmailStatusLog{Id=(int)读卡器[“Id”]、投资者代码=(字符串)读卡器[“投资者代码”]、EmailId=读卡器[“EmailId”]!=DBNull.Value?(字符串)读卡器[“EmailId”]:“”、日期=(字符串)读卡器[“日期”]、报告名=(字符串)读卡器[“报告名”]、导出状态=(bool)读卡器[“导出状态”]、EmailSendStatus=(bool)读卡器[“EmailSendStatus”],IsActive=(bool)读卡器[“IsActive”]});
}
}
}
返回消息;
}
private void dependency_OnChange(对象发送方,SqlNotificationEventArgs e)
{
if(e.Type==SqlNotificationType.Change)
{
StatusLogHub StatusLogHub=新的StatusLogHub();
statusLogHub.SendExportStatus();
}
}
}
//更新数据库的代码:
公共状态()
{
List lstmailstatuslog=新列表();
EmailStatusLog objEmailStatusLog=新的EmailStatusLog();
foreach(lstEmailReceipent中的var emailItem)
{
EMailDBContext _ctx=新的EMailDBContext();
objEmailStatusLog.EmailId=emailItem.stEmailAdd;
objEmailStatusLog.Investor_Code=emailItem.stInvestor_Code;
objEmailStatusLog.Date=DateTime.Now.ToString(“MM/dd/yyyy”);
objEmailStatusLog.ReportName=ReportName;
objEmailStatusLog.ExportStatus=IsSuccess;
objEmailStatusLog.EmailSendStatus=false;
objEmailStatusLog.IsActive=true;
_ctx.emailStatusLogs.Add(objEmailStatusLog);
_ctx.SaveChanges();
//StatusLogHub objStatusLogHub=新的StatusLogHub();
//objStatusLogHub.SendExportStatus();
}
}
控制器:
公共操作结果GetExportStatus()
{
EmailStatusLogRepository objEmailStatusRepository=新的EmailStatusLogRepository();
返回PartialView(“_exportedReportList”,objEmailStatusRepository.GetExportStatus());
}
Javascript:
//============================信号机
$(函数(){
var hub=$.connection.statusLog;
hub.client.updateStatus=函数(){
getExportStatus()
};
$.connection.hub.start().done(函数(){
警报(“连接已启动”);
//hub.server.sendExportStatus($('').val());
getExportStatus();
}).失败(功能(e){
警报(e);
});
});
函数getExportStatus(){
变量tbl=$(“#状态表”);
$.ajax({
url:'@url.Action(“GetExportStatus”),
contentType:'应用程序/html;字符集:utf-8',
键入:“GET”,
数据类型:“html”
}).成功(功能(结果){
tbl.empty().append(结果);
}).错误(函数(){
});
}

您需要更改客户端脚本和中心类方法。 在hub方法中,需要将GetExportStatus方法作为参数传递,以便hub将数据发送到所有客户端:

[HubName("statusLog")]
public class StatusLogHub : Hub
{

    [HubMethodName("sendExportStatus")]
    public void SendExportStatus()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatusLogHub>();
        EmailStatusLogRepository el = new EmailStatusLogRepository();
                Clients.All.updateStatus(el.GetExportStatus());
    }
}
您可以参考以下跨域链接:

您可以通过以下方式尝试客户端脚本:

$(function()
        {
            var hubstatusLog = $.connection.statusLog;
            hubstatusLog.client.updateStatus = function(data) {
//data contain all the data from repository this will call every time as repository updated
                getExportStatus(data)
           };
   $.connection.hub.start(function () {
hubstatusLog.server.sendExportStatus();
});
});

function getExportStatus(data)
        {
alert(data);
            //you can put here logic for getting data on html.
    }
服务器集线器:

    [HubName("statusLog")]
public class StatusLogHub : Hub
{

    [HubMethodName("sendExportStatus")]
    public void SendExportStatus()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatusLogHub>();
        EmailStatusLogRepository el = new EmailStatusLogRepository();
                Clients.All.updateStatus(el.GetExportStatus());
    }
}
[HubName(“状态日志”)]
公共类StatusLogHub:Hub
{
[HubMethodName(“sendExportStatus”)]
公共无效SendExportStatus()
{
IHubContext context=GlobalHost.ConnectionManager.GetHubContext();
EmailStatusLogRepository el=新的EmailStatusLogRepository();
Clients.All.updateStatus(el.GetExportStatus());
}
}

谢谢@Rahul,但我从客户端收到此错误:未捕获类型错误:无法在以下方法中读取未定义的属性“sendExportStatus:.connection.hub.start().done(函数(){hub.server.sendExportStatus();})。失败(函数(e){alert(e);})});我认为没有创建hub。所以请检查配置javascript中有一个异常:hub未定义谢谢@Rahul。但实际上我必须使用hub而不生成代理。你能对此给出任何建议吗?因此,你可以参考链接
    [HubName("statusLog")]
public class StatusLogHub : Hub
{

    [HubMethodName("sendExportStatus")]
    public void SendExportStatus()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatusLogHub>();
        EmailStatusLogRepository el = new EmailStatusLogRepository();
                Clients.All.updateStatus(el.GetExportStatus());
    }
}