How to make Fluent API configuration work with MVC client side validation?

后端 未结 2 537
执笔经年
执笔经年 2020-12-28 14:11

I prefer working with Fluent API configuration to DataAnnotation because I want to separate model from data access.

I have tried in MVC, Fluent API does not work wit

2条回答
  •  醉梦人生
    2020-12-28 14:56

    I struggled with this for a while today, and this is not strictly client validation as it requires a round trip, but it does allow you to benefit from the Validation summary and messages helpers in the standard template. Within your controller action method you simply wrap your SaveChanges() call in a try - catch and add the resulting Errors to the ModelState as follows:

    try {
    
        //This does not pick up fluent validation failures
        if (ModelState.IsValid) {
            db.Entity.Add(entity);
            db.SaveChanges();
            //Users want to create loads of my entities without seeing the index...
            return RedirectToAction("Create");
        }
    
    } catch (DbEntityValidationException e) {
    
        //Log errors
        foreach (var result in e.EntityValidationErrors) {
            foreach(var error in result.ValidationErrors){
                ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
            }
        }
    
    }
    
    //return to view with current model + validation errors 
    return View(entity)
    

    This would of course require a bit more work if you are saving multiple entities here.

    Of course using a View Model objects as Ladislav suggests would be the correct approach, however I have used this to support a test UI requested for downstream systems integration testing ahead of schedule...

提交回复
热议问题