如何在视图上显示DbEntityValidationException错误?

时间:2016-06-15 19:02:47

标签: c# .net asp.net-mvc entity-framework asp.net-mvc-4

我正在对我的模型执行一些跨属性验证,并且想知道在视图上显示这些错误的最佳方法。这就是我所拥有的:

CONTROLLER

[HttpPost]
public ActionResult Update(User user)
{
    if (ModelState.IsValid)
    {
        try
        {
            userManager.Update(user);
            return RedirectToAction("Index");
        }
        catch (DbEntityValidationException ex)
        {
           //not sure what to do here. 
        }
    }

    return View(user);
}

BUSINESS LOGIC LAYER(UserManager.cs)

public User Update(User user)
{
    ...

    try
    {
        _context.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        // Retrieve the error messages as a list of strings.
        var errorMessages = ex.EntityValidationErrors
                .SelectMany(x => x.ValidationErrors)
                .Select(x => x.ErrorMessage);

        // Join the list to a single string.
        var fullErrorMessage = string.Join("; ", errorMessages);

        // Combine the original exception message with the new one.
        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

        // Throw a new DbEntityValidationException with the improved exception message.
        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
    }

    return user;
}

CONTEXT(UserContext.cs)

protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
            try
            {
                    if (Users.Any(u => u.Id == ((User)entityEntry.Entity).Id && u.Name == ((User)entityEntry.Entity).Name))
                        return new DbEntityValidationResult(entityEntry, new List<DbValidationError>{
                                                                            new DbValidationError( "Id && Name", "Id and Name combination already added earlier")
                                                                         });

                    return base.ValidateEntity(entityEntry, items);
            }

我不确定的是,当异常到达控制器时,如何将这些模型错误返回到视图?有没有“MVC”的方法来做,或者我只需要将错误放在ViewBag中并自己显示它?

1 个答案:

答案 0 :(得分:0)

以下是我在评论中提出的建议,并让其他人知道此问题已得到解答。

ModelState.AddModelError(user.property, ex.message);

这将为您提供自定义错误消息,以显示在控制器的视图中。