ajax - Asp.net core - 如何使用signalR实现实时
问题描述
我正在我的项目中添加评论部分,我想使用 signalR 实时使用。我正在使用 Ajax 添加评论,我想在评论插入数据库后刷新所有用户的数据。
这是我在 Razor 视图中的代码:
<form asp-action="SendComment" asp-controller="Home" asp-route-subId="@Model.Subject.Id"
asp-route-AccountName="@User.Identity.Name" onsubmit="return jQueryAjaxPost(this);">
<textarea name="comment" id="myTextbox" required class="form-control mb-3" rows="3" cols="1" placeholder="اكتب هنا"></textarea>
<div class="d-flex align-items-center">
<button type="submit" id="myBtn" class="btn bg-blue-400 btn-labeled btn-labeled-right ml-auto"><b><i class="icon-paperplane"></i></b> ارسال</button>
</div>
</form>
阿贾克斯代码:
jQueryAjaxPost = form => {
try {
$.ajax({
type: 'POST',
url: form.action,
data: new FormData(form),
contentType: false,
processData: false,
success: function (res) {
if (res.isValid) {
$('#view-all').html(res.html)
}
else
$('#form-modal .modal-body').html(res.html);
},
error: function (err) {
console.log(err)
}
})
//to prevent default form submit event
return false;
} catch (ex) {
console.log(ex)
}
}
signalR 代码(未完成)
<reference path="../lib/signalr/browser/signalr.js" />
$(() => { 让连接 = new signalR.HubConnectionBuilder().withUrl("/signalServer").build();
connection.start();
connection.on("refreshData", function () {
loadData();
});
loadData();
function loadData() {
debugger;
$.ajax({
type: 'GET',
url: '@Url.Action("refreshComments","Home")',
success: function (res) {
$('#view-all').html(res);
}
})
}
});
代码隐藏:
var newComment = new CourseComment
{
Comment = comment,
Date = DateTime.Now,
ApplicationUser = user,
SubjectId = subId,
CreatedDate = DateTime.Now
};
_courseCommnt.Entity.Insert(newComment);
await _courseCommnt.SaveAsync();
await _signalR.Clients.All.SendAsync("refreshData");
_toastNotification.AddSuccessToastMessage("تم ارسال التعليق بنجاح");
var courseComments = await _courseCommnt.Entity.GetAll().Include(a => a.ApplicationUser)
.Where(a => a.SubjectId == subId).OrderByDescending(a => a.Date).AsNoTracking().ToListAsync();
var vm = new HomeViewModel
{
CourseComments = courseComments
};
return Json(new
{
isValid = true,
html = Helper.RenderRazorViewToString(this, "_SubjectComments", vm)
});
解决方案
推荐阅读
- css - 滑块图像加载时间和显示问题
- android - v3.2 安卓资源编译失败
- c# - 为什么我的 Azure 函数没有在 App Insights 中记录正确的异常?
- python-3.x - 将 for 循环的结果添加到嵌套字典中的相同键
- javascript - 用于验证字段的正则表达式
- javascript - 将 Google 驱动器中的图像插入工作表
- azure - 复制完成后 CloudBlockBlob.StartCopyAsync 是否返回?
- node.js - 无法从 node/react 访问生产中的 graphql
- javascript - 子元素上的 className 影响父元素
- arduino - 堆叠数据,提取价值,下推堆栈