1

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.

ben
  • 29,229
  • 42
  • 124
  • 179

5 Answers5

2

You can have a ViewModel pattern see this ASP.NET MVC ViewModel Pattern

Community
  • 1
  • 1
ajay_whiz
  • 17,573
  • 4
  • 36
  • 44
0

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); }
lohiaguitar91
  • 522
  • 5
  • 9
0

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 ).

0

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

0

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

happyhardik
  • 24,987
  • 7
  • 47
  • 60