Новичок. Blazor не понимает, почему мой метод удаления не запускает [закрыто]C#

Место общения программистов C#
Ответить
Anonymous
 Новичок. Blazor не понимает, почему мой метод удаления не запускает [закрыто]

Сообщение Anonymous »

Я немного новичок. Мне жаль, что, если на этот вопрос уже ответил, я еще не смог найти решение. Когда я запускаю приложение и выбираю, чтобы удалить продукт, модал висит. Я не могу либо удалить или отменить модал. Я могу закрыть модал, нажав на крест. < /P>
для других методов. Создать, обновить модал работает нормально. Просто удаленный не работает. < /P>
indexpage < /p>
@page "/product"

@using BlazorApp.Models.Entities
@using BlazorApp.Models.Models
@using BlazorappReal.Web.Components.BaseComponent
@using Newtonsoft.Json

@using Microsoft.AspNetCore.Components;
@using Blazored.Toast.Services;

@inject ApiClient _apiClient
@inject IToastService _toastService

@inherits ComponentBase // I Think this is implicit blazor does this by defualt ?

IndexProduct

@if(ProductModels == null)
{
Loading...
}
else
{
Create




ProductName
Quantity
Price
Description
CreatedAt
Action



@foreach(var product in ProductModels)
{

@product.ProductName
@product.Quantity
@product.Price
@product.Description
@product.CreatedAt.ToShortDateString()

Update
Delete


}




Notification

Are you sure you want to delete this product ?


Yes
Cancel


}

@code {

// [Inject]
// public ApiClient ApiClient{ get; set; }

// [Inject] // TODO: May not need this
// private IToastService ToastService { get; set; }

public List ProductModels { get; set; }

public AppModal Modal { get; set; }

public int DeleteID { get; set; }

protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
await LoadProduct();
}

protected async Task LoadProduct()
{
// var result = await ApiClient.GetFromJsonAsync("/api/Product");
var result = await _apiClient.GetFromJsonAsync("/api/Product");
if (result != null && result.Success)
{
ProductModels = JsonConvert.DeserializeObject(result.Data.ToString());
}
await base.OnInitializedAsync();
}

protected async Task HandleDelete()
{
// var result = await ApiClient.DeleteAsync($"/api/Product/{DeleteID}");
var result = await _apiClient.DeleteAsync($"/api/Product/{DeleteID}");
if(result != null && result.Success)
{
// ToastService.ShowSuccess("Product deleted successfully");
_toastService.ShowSuccess("Product deleted successfully");
await LoadProduct();
Modal.CloseModal();
}
}
}
< /code>
using Newtonsoft.Json;
using System.IO;

namespace BlazorappReal.Web;

public class ApiClient(HttpClient httpClient)
{
public Task GetFromJsonAsync(string path)
{
return httpClient. GetFromJsonAsync(path);
}

public async Task PostAsync(string path, T2 postModel)
{
var result = await httpClient.PostAsJsonAsync(path, postModel);
if(result != null && result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject(await result.Content.ReadAsStringAsync());
}
return default;
}

// Update ??
public async Task PutAsync(string path, T2 postModel)
{
var result = await httpClient.PutAsJsonAsync(path, postModel);
if (result != null && result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject(await result.Content.ReadAsStringAsync());
}
return default;
}

public Task DeleteAsync(string path)
{
return httpClient.DeleteFromJsonAsync(path);
}
}
< /code>
using BlazorApp.BuisnessLogic.Repositories;
using BlazorApp.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BlazorApp.BuisnessLogic.Services
{
public interface IProductService
{
Task GetProducts();
Task GetProduct(int id);
Task CreateProduct(ProductModel productModel);

Task ProductModelExist(int id);

Task UpdateProduct(ProductModel productModel);
Task DeleteProduct(int id);
}

// Using Di to provide the instance of the productRepository
public class ProductService(IProductRepository productRepository) : IProductService
{
public Task GetProducts()
{
return productRepository.GetProducts();
}

public Task GetProduct(int id)
{
return productRepository.GetProduct(id);
}

public Task CreateProduct(ProductModel productModel)
{
return productRepository.CreateProduct(productModel);
}

public Task ProductModelExist(int id)
{
return productRepository.ProductModelExist(id);
}

public Task UpdateProduct(ProductModel productModel)
{
return productRepository.UpdateProduct(productModel);
}

public Task DeleteProduct(int id)
{
return productRepository.DeleteProduct(id);
}
}
}
< /code>
using BlazorApp.Database.Data;
using BlazorApp.Models.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BlazorApp.BuisnessLogic.Repositories
{

public interface IProductRepository
{
Task GetProducts();
Task GetProduct(int id);
Task CreateProduct(ProductModel productModel);
Task ProductModelExist(int id);
Task UpdateProduct(ProductModel productModel);
Task DeleteProduct(int id);
}
public class ProductRepository(AppDbContext dbContext) : IProductRepository
{
public Task GetProducts()
{
return dbContext.Products.ToListAsync(); // return a list of products from the db
}
public Task GetProduct(int id)
{
// The lambda returns the product(n) whose ID matches the given id, or null if no match exists.
return dbContext.Products.FirstOrDefaultAsync(n => n.ID == id);
}

public async Task CreateProduct(ProductModel productModel)
{
dbContext.Products.Add(productModel);
await dbContext.SaveChangesAsync();
return productModel;
}

public async Task ProductModelExist(int id)
{
return await dbContext.Products.AnyAsync(e => e.ID == id);
}

public async Task UpdateProduct(ProductModel productModel)
{
dbContext.Entry(productModel).State = EntityState.Modified;
await dbContext.SaveChangesAsync();
}

public async Task DeleteProduct(int id)
{
var productToDelete = dbContext.Products.FirstOrDefault(n => n.ID == id);
dbContext.Products.Remove(productToDelete);
await dbContext.SaveChangesAsync();
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... triggering
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»