Я немного новичок. Мне жаль, что, если на этот вопрос уже ответил, я еще не смог найти решение. Когда я запускаю приложение и выбираю, чтобы удалить продукт, модал висит. Я не могу либо удалить или отменить модал. Я могу закрыть модал, нажав на крест. < /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
Новичок. Blazor не понимает, почему мой метод удаления не запускает [закрыто] ⇐ C#
Место общения программистов C#
1759775376
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
{
[url=/product/create]Create[/url]
ProductName
Quantity
Price
Description
CreatedAt
Action
@foreach(var product in ProductModels)
{
@product.ProductName
@product.Quantity
@product.Price
@product.Description
@product.CreatedAt.ToShortDateString()
[url=/product/update/@product.ID]Update[/url]
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();
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79783891/newbie-blazor-not-understanding-why-my-delete-method-is-not-triggering[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия