У меня есть страница, где люди могут создавать заметки, они добавляются на страницу через ajax. Мне нужно реализовать функциональность SignalR для обновления страницы при создании нового элемента.
Исходя из ваших требований, я создаю следующий образец, который хорошо работает на моей стороне, пожалуйста, обратитесь к нему.
Класс ступицы
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.Others.SendAsync("NoteUpdateNotification", user, message);
}
}
Указатель
@model IEnumerable<NotesRTMSignalR.Models.NoteInfo>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>
@section Scripts {
<style>
.newnote{
background-color:yellow;
}
</style>
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("NoteUpdateNotification", function (user, message) {
console.log(user + " updated/added a note, the details is '" + message + "'");
$("tr.newnote").removeClass("newnote");
var note = JSON.parse(message);
var tr = "<tr class='newnote'><td>" + note.Id +
"</td><td>" + note.Title +
"</td><td>" + note.Description +
"</td><td>" + note.Author +
"</td><td><a href=''>Edit</a> |<a href=''>Details</a> |<a href=''>Delete</a></td></tr>"
$("tbody").append(tr);
});
connection.start().then(function () {
console.log("connection started");
}).catch(function (err) {
return console.error(err.toString());
});
</script>
}
Создать страницу
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//connection.on("NoteUpdateNotification", function (user, message) {
// alert(user + " updated/added a note, the details is '" + message + "'");
//});
connection.start().then(function () {
console.log("connection started");
}).catch(function (err) {
return console.error(err.toString());
});
$(function () {
$("input[type='submit']").click(function (e) {
var note = { "Id": $("input[id='Id']").val(), "Title": $("input[id='Title']").val(), "Description": $("input[id='Description']").val(), "Author": $("input[id='Author']").val() };
//alert(JSON.stringify(note));
$.ajax({
url: "/Note/CreateNote",
type: "POST",
data: JSON.stringify(note),
contentType: "application/json",
success: function (res) {
connection.invoke("SendMessage", $("input[id='Author']").val(), JSON.stringify(note)).catch(function (err) {
return console.error(err.toString());
});
alert("Note Update/Add Notification Is Sent To Others");
},
failure: function (err) {
}
})
e.preventDefault();
})
})
</script>
Результат теста
![enter image description here](https://i.stack.imgur.com/tsGQZ.gif)
Примечание : вы можете начать с ASP.NET Core SignalR , а затем настроить клиентское приложение SignalR JavaScript в соответствии с вашим сценарием и требованиями.