vendredi 3 février 2023

Dealing with complex ViewModels that have many forms in C#

I'm developing some kind of library management ASP.NET Core 5 MVC Web App, this system circulates around the functionality of doing CRUD operations on Library Materials, a Material has almost 19 types (Book, Article.. etc), each type can have up to 29 form fields some are optional some are required, and each type share alot of fields with other types.
in the DB i have one table (Material) that contain all of the fields.

I'm trying to figure out what would be the best approach to deal with creating and updating Materials when it comes to the ViewModels side, I'm thinking of creating a hierarchy where i have one BaseMaterialVM that have the base material properties that are shared, and have each of the 19 types as ViewModels (BookVM.. etc) relate to it in some way so that the shared fields aren't duplicated, and each ViewModel has one form partial view (for example _BookForm.. etc).

at first i thought of using Inheritance so that i have one virtual class MaterialVM containing all the form fields as properties with no data annotations on them and have BaseMaterialVM inherit from it and have each type of the 19 types inherit from the BaseMaterialVM, the validation and the data annotations are done in the inherited classes, but once say _BookForm is submitted to the endpoint:

[HttpPost()]
public IActionResult Add(MaterialVM vm) {
  if(ModelState.IsValid()){     
  //Convert to ef model, add to DB  
  }   
}

i expected MaterialVM would have the validations automatically from the inherited classes, unfortunately that doesn't happen, MaterialVM is always valid in this case.

is there anyway to have the data annotations and validations automatically from the inherited classes?

also if there's any better approaches to deal with the complexity of the Material forms other than ViewModel inheritance, please let me know.

Aucun commentaire:

Enregistrer un commentaire