Context
In my application I use the MVVM pattern. I'll have a ViewModel that can contains information of a student. This viewmodel is used to communicate between my view and model. I use ASP.net core MVC whit vue.js.
My project contains out of the following elements:
- Views (UI)
- Controller API (responsible for responding to requests from the view)
- Models (logic)
- ViewModels(Containing information for the views)
- Repository (repository pattern for communicating whit database)
Senario
When the end user creates for example a student it will fill in some data and and press button to safe the student. Now the information will be send to the server whit a ajax call. The Controller API now catches the HTTP request and cast it to the view model.
Controller API
[HttpPut]
public JsonResult Put([FromBody] StudentViewModel studentViewModel)
{
//...
}
This is the process in steps:
- The view makes an ajax request to the Controller Api. This request has all the property's of the StudentViewModel so it can be parsed in the Controller Api.
- The Controller Api takes in the information and will parse it to the StudentViewModel
- The Controller Api asks the repository to create a new student from the StudentViewmodel.
- The repository will create a new student from the information in the StudentViewModel
I have my data acces layer wrapped in repository pattern. It will look something like this:
Controller API
[HttpPut]
public JsonResult Put([FromBody] StudentViewModel studentViewModel)
{
using (var db = new UserQuery(DatabaseContext.GetInstance()))
{
// creates a user based on the information in the viewmodel
db.Students.CreateNew(studentViewModel);
}
}
But for some reason I do not like this approach. Because I now have my View layer and data layer depend on the same viewmodel. The view is heavily bound to
the StudentViewModel because the data it provide should be convertible and this same VieModel is used for the database to create a new user.
Question
Is there a better way for this scenario? Or is this just fine.