@page "/contacts/edit/{id:int}"
@page "/contacts/new"
@inject HttpClient Http
@inject NavigationManager NavigationManager
@if (Id is not null)
{
Edit @contact.NickName
}
else
{
Create a new contact
}
Contact saved successfully.
Oops, something went wrong.
@if(Id is not null)
{
Notes
@foreach(var note in notes)
{
}
}
@code {
[Parameter]
public int? Id { get; set; }
public Contact contact { get; set; } = new Contact();
public List notes { get; set; } = new List();
public Note newNote { get; set; } = new Note { Text = string.Empty };
bool showSuccessMessage = false;
bool showErrorMessage = false;
protected override async Task OnInitializedAsync()
{
if(Id is not null)
{
var result = await Http.GetAsync($"api/contacts/{Id}");
if (result.IsSuccessStatusCode)
{
var jsonResult = await result.Content.ReadFromJsonAsync();
if (jsonResult is not null)
contact = jsonResult;
}
else
{
NavigationManager.NavigateTo("/contacts/new");
}
}
}
async Task HandleSubmit()
{
HttpResponseMessage result;
if (Id is not null)
result = await Http.PutAsJsonAsync($"api/contacts/{contact.Id}", contact);
else
result = await Http.PostAsJsonAsync($"api/contacts/", contact);
if (result.IsSuccessStatusCode)
{
var jsonResult = await result.Content.ReadFromJsonAsync();
if(jsonResult is not null)
{
contact = jsonResult;
showSuccessMessage = true;
}
}
else
{
showErrorMessage = true;
}
}
async Task CreateNote()
{
if (Id is null)
return;
newNote.ContactId = Id;
var result = await Http.PostAsJsonAsync($"api/notes", newNote);
if (result.IsSuccessStatusCode)
await LoadNotes();
}
async Task DeleteNote(int noteId)
{
var result = await Http.DeleteFromJsonAsync>($"api/notes/{noteId}");
if (result is not null)
notes = result;
}
async Task LoadNotes()
{
var result = await Http.GetFromJsonAsync>($"api/notes/{contact.Id}");
if (result is not null)
notes = result;
}
}