ben
ben

Reputation: 29767

Simple question about MVC

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.

Upvotes: 1

Views: 280

Answers (5)

Plamen Radinski
Plamen Radinski

Reputation: 13

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

Upvotes: 0

user2190358
user2190358

Reputation: 1

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

Upvotes: 0

lohiaguitar91
lohiaguitar91

Reputation: 522

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); }

Upvotes: 0

happyhardik
happyhardik

Reputation: 25537

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

Upvotes: 0

ajay_whiz
ajay_whiz

Reputation: 17931

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

Upvotes: 2

Related Questions