gpt4 book ai didi

c# - ASP.NET MVC : How can I get my business rule validation to bubble up to the presentation layer?

转载 作者:太空狗 更新时间:2023-10-29 21:41:50 26 4
gpt4 key购买 nike

对于我的每个业务实体,我都有相应的 View 模型。

我有一个像这样工作的通用 CRUD Controller :

    [HttpPost]
public virtual ActionResult Create(TViewModel model, int? id)
{
// Validate input
if (!ModelState.IsValid)
return Json(Failure(createView, model.SelectLists(repository)));

// Prepare Model
var entity = new TModel();

// Add to repository
UpdateModel(entity);
repository.Add(entity);
repository.Save();
return Json(CreateSuccess(entity));
}

我在我的 View 模型属性上使用数据注释,这对于简单的输入验证非常有用。

现在我有一个案例,我想确保不会意外创建重复记录。

我的第一直觉是将此逻辑放在存储库的 Add 方法中。这个实现很简单,但是我如何让存储库添加模型状态错误并向用户返回一些有用的信息?我觉得必须有一个解决方案,但我没有找到太多运气。

感谢您的帮助!

最佳答案

我会使用异常(exception)。

  • 如果实体加倍,则在 Add 方法中抛出自定义应用程序异常。
  • 将 Add 方法包装在 try block 中,以在 Create 方法中捕获此特定异常。
  • 在 catch block 中添加基于异常数据的模型状态错误

    try
    {
    repository.Add(entity);
    }
    catch(MyRepositoryException ex)
    {
    ViewData.ModelState.AddModelError(ex.Key, ex.Value.ToString(), ex.Message)
    }

    if (!ModelState.IsValid)
    return Json(Failure(createView, model.SelectLists(repository)));

关于c# - ASP.NET MVC : How can I get my business rule validation to bubble up to the presentation layer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4823994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com