C
C#6mo ago
Ares

How do I refresh view data from inside of a view?

I have a SignalR setup, and I have it where when I press on a button, it will send a message to the server and then the server will then broadcast the message to all clients. The problem I am having is, when a client receives the emission from the server, how can I refresh the data that is on the page? I want it so that when the client receives the server message, it will refresh the data that is being displayed on the homepage. I dont want to refresh the entire page because that kind of defeats the purpose of websockets. Any advice?
3 Replies
Ares
Ares6mo ago
//Views/Poll/Index.cshtml
@model realTimePolls.Models.PollsViewModel

<form asp-controller="Poll" asp-action="Vote" method="post" id="form">
<div class="vote-flex">
<label for="VoteFirst">@Model.Poll.FirstOption</label><br>
<input type="radio" id="vote-first" name="vote" value="Vote First" @(Model.UserPoll != null && Model.UserPoll.FirstVote == true ? "checked" : "")>
<br />
<label for="vote-second">@Model.Poll.SecondOption</label><br>
<input type="radio" id="vote-second" name="vote" value="Vote Second" @(Model.UserPoll != null && Model.UserPoll.SecondVote == true ? "checked" : "")>
<br />
<input type="hidden" name="pollid" value="@Model.Poll.Id" />
<input type="hidden" name="userid" value="@Model.Poll.UserId" />
<button type="submit" id="vote-btn"> Submit Vote</button>
<input type="button" value="Delete" onclick="location.href='@Url.Action("Delete", "Poll", new { pollid = Model.Poll.Id })'" />
</div>
</form>
//Views/Poll/Index.cshtml
@model realTimePolls.Models.PollsViewModel

<form asp-controller="Poll" asp-action="Vote" method="post" id="form">
<div class="vote-flex">
<label for="VoteFirst">@Model.Poll.FirstOption</label><br>
<input type="radio" id="vote-first" name="vote" value="Vote First" @(Model.UserPoll != null && Model.UserPoll.FirstVote == true ? "checked" : "")>
<br />
<label for="vote-second">@Model.Poll.SecondOption</label><br>
<input type="radio" id="vote-second" name="vote" value="Vote Second" @(Model.UserPoll != null && Model.UserPoll.SecondVote == true ? "checked" : "")>
<br />
<input type="hidden" name="pollid" value="@Model.Poll.Id" />
<input type="hidden" name="userid" value="@Model.Poll.UserId" />
<button type="submit" id="vote-btn"> Submit Vote</button>
<input type="button" value="Delete" onclick="location.href='@Url.Action("Delete", "Poll", new { pollid = Model.Poll.Id })'" />
</div>
</form>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

<script>
const hubConnection = new signalR.HubConnectionBuilder()
.withUrl("/pollHub")
.configureLogging(signalR.LogLevel.Information)
.build();

async function start() {
try {
await hubConnection.start();
console.log("SignalR Connected.");
} catch (err) {
console.log(err);
setTimeout(start, 5000);
}
};

hubConnection.onclose(async () => {
await start();
});

// Start the connection.
start();

const testBtn = document.getElementById("vote-btn")
testBtn.addEventListener('click', async (e) => {
e.preventDefault()
try {
await hubConnection.invoke("SendMessage", "fork", "HEY!!!!!");
} catch (err) {
console.error(err.toString());
}
})

hubConnection.on("ReceiveMessage", function (user, message) {
console.log(`${user} says ${message}`); //how do i refresh the data instead of console.log?
});

</script>
<script>
console.log(@Html.Raw(Json.Serialize(Model)))
</script>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>

<script>
const hubConnection = new signalR.HubConnectionBuilder()
.withUrl("/pollHub")
.configureLogging(signalR.LogLevel.Information)
.build();

async function start() {
try {
await hubConnection.start();
console.log("SignalR Connected.");
} catch (err) {
console.log(err);
setTimeout(start, 5000);
}
};

hubConnection.onclose(async () => {
await start();
});

// Start the connection.
start();

const testBtn = document.getElementById("vote-btn")
testBtn.addEventListener('click', async (e) => {
e.preventDefault()
try {
await hubConnection.invoke("SendMessage", "fork", "HEY!!!!!");
} catch (err) {
console.error(err.toString());
}
})

hubConnection.on("ReceiveMessage", function (user, message) {
console.log(`${user} says ${message}`); //how do i refresh the data instead of console.log?
});

</script>
<script>
console.log(@Html.Raw(Json.Serialize(Model)))
</script>
https://github.com/ForkEyeee/realtime-poll i can use js to fetch from a RefreshData Controller and then update the ui, but is there a better way to doit
Angius
Angius6mo ago
If you want to do it without reloading the page then yes, you will need to use JS You can receive JSON with data from the SignalR connection, use it to create a new HTML element, and append it anywhere you need in the DOM Alternatively, what some frameworks like HTMX, LiveWire, LiveWiew, etc. do, is they send the whole HTML element rendered on the server, so you just append that to the DOM
Ares
Ares6mo ago
ok i used js to do it it seems to work fine. seemed kinda scuffed though at first to do it that way thats why i asked
Want results from more Discord servers?
Add your server
More Posts
✅ Why is an explicit cast needed even though the implicit cast operator is available?No explicit cast is needed. ```csharp var (x, y) = GetPoint(); static (float re, float im) GetPoint(Need help in getting my dice to hold and release in a yahtzee type game.I am having issues with being able to hold and release dice in a yahtzee game. This was working, buTrying to read from a binary fileNew to c#, trying to validate a username and password from a binary file, but getting the issue 'TooHow to pass a Type to a method for a return of the same typeStruggling to find the right syntax for this. I'm trying to specify a type that should be used to crmathim brand new to C# and Im making a wage calculator but the math is wrong, it keeps rounding the outpSystem.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: APostmanden has an API written with the GET method that we can access from the browser without any prArray exceptionI can't for the life of me figure out this exception. ive identified that it comes from neurons becaModels&sqlHello, i created three new models: Tag UserTags PostTags the usertags and posttags were meant to holBlazor WASM in NET 8component not being recognizedI created components that are all recognized in VS2022, simply create a Razor Component, inherit Com✅ Bug in trying to replicate an unmodified array in a Winforms Sorting Algorithm ApplicationI have a weird bug in my C# Winform program. Here are the steps before I encountered this error: 1)