Blazor Server中如何在服务类内控制前端显示重复提示信息
解决Blazor Server分类重复提示问题
方案一:自定义异常处理
通过在服务类中抛出自定义异常,Razor页面捕获后直接设置提示信息,判断逻辑完全保留在服务层:
- 定义自定义异常类(可放在服务所在程序集):
public class DuplicateCategoryException : Exception { public DuplicateCategoryException(string message) : base(message) { } }
- 修改服务类的Add方法:
public async Task<Category> Add(string categoryName) { if (_context.Category.Any(c => c.Name == categoryName)) { throw new DuplicateCategoryException("Already exists"); } var cat = new Category { Name = categoryName }; await _context.AddAsync(cat); await _context.SaveChangesAsync(); return cat; }
- 修改Razor页面的调用方法:
protected async Task IncrementCount() { try { category = await _categoryService.Add("test"); errorMessage = string.Empty; } catch (DuplicateCategoryException ex) { errorMessage = ex.Message; category = null; } }
方案二:返回包含结果和错误的DTO
创建专用数据传输对象,让服务直接返回操作结果与错误信息,前端无需自行判断空值:
- 定义DTO类:
public class CategoryOperationResult { public Category Category { get; set; } public string ErrorMessage { get; set; } = string.Empty; public bool IsSuccess => string.IsNullOrEmpty(ErrorMessage); }
- 修改服务类的Add方法:
public async Task<CategoryOperationResult> Add(string categoryName) { if (_context.Category.Any(c => c.Name == categoryName)) { return new CategoryOperationResult { ErrorMessage = "Already exists" }; } var cat = new Category { Name = categoryName }; await _context.AddAsync(cat); await _context.SaveChangesAsync(); return new CategoryOperationResult { Category = cat }; }
- 修改Razor页面的调用方法:
protected async Task IncrementCount() { var result = await _categoryService.Add("test"); category = result.Category; errorMessage = result.ErrorMessage; }
两种方案均满足要求:重复判断逻辑完全保留在服务类中,前端仅需处理返回结果或捕获异常即可展示提示信息。
内容的提问来源于stack exchange,提问作者Manta
相关产品推荐
相关产品推荐

