I am new to Blazor and I have a question about Blazor and API.
In my .razor
file, I have this code where I am able to get the data to fill in in my table (so this code works):
@code {
public PrgUser[] users { get; set; }
IList<PrgUser> selectedUser;
protected override async Task OnInitializedAsync()
{
users = await Http.GetFromJsonAsync<PrgUser[]>("http://localhost:30958/api/Test");
selectedUser = users.Take(1).ToList();
}
}
And this code works great with the following code on the API side:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly IneosAppDevContext _context;
public TestController(IneosAppDevContext context)
{
_context = context;
}
// GET: api/Areas
[HttpGet]
public async Task<ActionResult<IEnumerable<PrgUser>>> GetUser()
{
return await _context.PrgUser.ToListAsync();
}
}
But now I want do add a DELETE
function but I can't figure out how to do this. I have this code, but it doesn't work this way...
.razor
file:
@code {
public PrgUser[] users { get; set; }
IList<PrgUser> selectedUser;
protected override async Task OnInitializedAsync()
{
users = await Http.GetFromJsonAsync<PrgUser[]>("http://localhost:30958/api/Test");
selectedUser = users.Take(1).ToList();
}
protected async Task Enter()
{
Console.WriteLine("Pressed");
var response = await Http.DeleteAsync("http://localhost:30958/api/Test/" + selectedUser[0].UserId);
}
}
API side:
[HttpDelete]
[Route("/api/Test/{id}")]
public async Task<HttpResponseMessage> Delete(int id)
{
var user = await _context.PrgUser.FindAsync(id);
if (user == null)
{
// if ID not found
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
try
{
// Success
_context.PrgUser.Remove(user);
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception ex)
{
// Exception
return new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
}