Let's say I have two objects, A and B, both with a model, view and a controller. The user is in the view for A, then presses a button or something that calls an action in the A controller. This action requires some use of the B model. From the action in the A controller, am I supposed to call directly to the B model, or should I be going through the B controller to interact with the B model? Thanks for reading.
5 Answers
If the objects have a relation between them (for example, a many-to-many relation between question and answer), you can give your object A model a list of object B models (and vice-versa)
In your model class for object A, this would look like:
[Key]
[Display(Name = "Primary Key")]
public int QuestionId{ get; set; }
public virtual IList<Answer> Answers{ get; set; }
And similarly for object B (Answers, which has an IList of Questions)
This allows you to call Object B (Answer) in your Controller as object.answers
or however you have it structured.
You'll likely have to add the many-to-many relation OnModelBuild()
like:
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Entity<Question>().HasMany(a => a.Answers).WithMany(b => b.Questions); }

- 522
- 5
- 9
You should never call B controller from A or vice verse, Cause in this way you are making an application that will be too strict ! You should always decouple your application. Imagine you change the working for controllers B's method which was being used by A controller, you will be stuck. A better way is to create another layer which handles all this and the controllers should just call the layers, For ex: Business Layer(BLL) : Having UserBLL.cs -> having a method : Authenticate(string username,string password){}
Your Controller A and B both can call up this layer(UserBLL.cs) and utilize it.This way the application will be Robust and decoupled. Better should create another layer,a Repository layer (For Crud operations ).
You can either create a viewmodel containing both models
Model A {} Model B{}
ViewModel AB{
Model A;
Model B;
}
//Custom model binder if you want to pass the ViewModel
public ActionResult SomeAction(Model A, Model B) {
//Logic
//pass the ViewModel(A,B) to the View
}
Or you can pass the control to the controller that handles the B model logic. The last scenario I can think of is creating a B Service which gets the A model and does the logic

- 13
- 3
I guess you should go through the B controller as B controller has access to B model.

- 24,987
- 7
- 47
- 60
-
1What do you mean, "only has access?" There's no reason it HAS to be that way. – Matthew Olenik Sep 07 '10 at 06:30
-
oops! removed the word "only". – happyhardik Sep 07 '10 at 06:39