98 lines
2.6 KiB
Plaintext
98 lines
2.6 KiB
Plaintext
|
@page "/"
|
||
|
@using LiveChat.Models;
|
||
|
@using Microsoft.AspNetCore.SignalR.Client
|
||
|
@inject NavigationManager Navigation
|
||
|
@implements IAsyncDisposable
|
||
|
|
||
|
<PageTitle>LiveChat app</PageTitle>
|
||
|
|
||
|
<p>Sortert fra topp-bunn</p>
|
||
|
|
||
|
@if (msgs != null)
|
||
|
{
|
||
|
<div class="MessagesList" id="messagesList">
|
||
|
@foreach (var message in msgs)
|
||
|
{
|
||
|
<div class="message">@message</div>
|
||
|
}
|
||
|
</div>
|
||
|
} else
|
||
|
{
|
||
|
<h1>Ingen meldinger tilgjengelig.</h1>
|
||
|
}
|
||
|
|
||
|
<div class="messageFormContainer">
|
||
|
@if (messageModel == null)
|
||
|
{
|
||
|
<p>laster inn meldingsboks</p>
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
<EditForm Model="@messageModel" OnValidSubmit="@HandleSubmit" class="MessageForm">
|
||
|
<DataAnnotationsValidator />
|
||
|
<div class="MessageFormValidation">
|
||
|
<ValidationSummary />
|
||
|
</div>
|
||
|
|
||
|
<div class="MessageFormInputs">
|
||
|
<input @bind-value="messageModel.User" placeholder="Navn" class="MessageFormName" />
|
||
|
<input @bind-value="messageModel.Message" placeholder="Skriv inn din melding..." class="MessageFormMessage" />
|
||
|
<button type="submit" disabled="@(!IsConnected)" class="MessageFormButton">Send melding!</button>
|
||
|
</div>
|
||
|
</EditForm>
|
||
|
}
|
||
|
</div>
|
||
|
@code {
|
||
|
private HubConnection? hubConnection;
|
||
|
private MessageModel messageModel = new MessageModel() { User = "", Message = "" };
|
||
|
private List<string> msgs = new List<string>();
|
||
|
|
||
|
|
||
|
protected override async Task OnInitializedAsync()
|
||
|
{
|
||
|
Console.WriteLine(messageModel);
|
||
|
hubConnection = new HubConnectionBuilder()
|
||
|
.WithUrl(Navigation.ToAbsoluteUri("/chathub"))
|
||
|
.Build();
|
||
|
|
||
|
using (var db = new ChattingContext())
|
||
|
{
|
||
|
var messages = db.Messages.ToList();
|
||
|
|
||
|
foreach (var msg in messages)
|
||
|
{
|
||
|
var encodedMsg = $"{msg.User}: {msg.Message}";
|
||
|
msgs.Add(encodedMsg);
|
||
|
InvokeAsync(StateHasChanged);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
hubConnection.On<string, string>("ReceiveMessage", (user, message) => {
|
||
|
var encodedMsg = $"{user}: {message}";
|
||
|
msgs.Add(encodedMsg);
|
||
|
InvokeAsync(StateHasChanged);
|
||
|
});
|
||
|
|
||
|
await hubConnection.StartAsync();
|
||
|
}
|
||
|
|
||
|
private async Task HandleSubmit()
|
||
|
{
|
||
|
if (hubConnection is not null)
|
||
|
{
|
||
|
await hubConnection.SendAsync("SendMessage", messageModel.User, messageModel.Message);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public bool IsConnected =>
|
||
|
hubConnection?.State == HubConnectionState.Connected;
|
||
|
|
||
|
public async ValueTask DisposeAsync()
|
||
|
{
|
||
|
if (hubConnection is not null)
|
||
|
{
|
||
|
await hubConnection.DisposeAsync();
|
||
|
}
|
||
|
}
|
||
|
}
|