I've this scenario in my application:
Controller1
Model1
Controller2
Model2
In this scenario Controller1.GetItems() calls Model1.GetItems() method. Model1.GetItems() method needs to know (for example) what is the role of the current user to build the correct list of items, and it should get it from the Model2.CurrentUser property (that stores the cached information about the current user).
Is it a good practice to acces a model from another model?
Thanks, Regards
In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.
The @model directive allows access to the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml view, the code loops through the movies with a foreach statement over the strongly typed Model object: CSHTML Copy.
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
You are going to run into some arguments about the best way to do this, but at the end of the day, you have two options. Either you can have the model pull the information it needs from the other model or you can have the controller pass the information needed.
Based upon what I have read, as long as the model does not have any controller logic or view logic you are good so there is nothing wrong with having the model know about other models. However, others have argued that having the controller pass the information that is needed makes the code a bit easier to document since you can see that the model requires information from somewhere else. At the end of the day though, I see both as being valid and which one you choose to use will likely come down to personal preference.
Design - Controller Provides Data
ModelOne
- User GetCurrentUser()
ModelTwo
- Items[] GetItems(User)
Snippet - Controller Proivdes Data
Controller {
function doWork() {
User user = ModelOne.GetCurrentUser();
Items[] items = ModelTwo.GetItems(user);
}
}
Design - Model Gets Data
ModelOne
- User GetCurrentUser()
ModelTwo
- Items[] GetItems()
Snippet - Model Gets Data
ModelTwo {
Items[] GetItems() {
User user = ModelOne.GetCurrentUser();
...
}
}
Controller {
function doWork() {
Items[] items = ModelTwo.GetItems();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With