Junior — Middle
Can you describe how the components of the model, view, and controller in the MVC architecture interact with each other?
sobes.tech AI
Answer from AI
In MVC (Model-View-Controller) architecture, components interact as follows:
-
Model: responsible for data and business logic. It stores the application's state and notifies the controller or view of changes.
-
View: displays data to the user. It receives information from the model and updates when changes occur.
-
Controller: accepts user input, processes it, modifies the model, and determines which view to display.
Interaction example:
- The user interacts with the interface (View), for example, clicking a button.
- The controller receives the event, processes it, possibly changing data in the model.
- The model updates its state and notifies the View of changes.
- The View updates the data display.
In C#, it might look like this:
// Model
public class Product {
public string Name { get; set; }
}
// Controller
public class ProductController {
private Product model;
private ProductView view;
public ProductController(Product model, ProductView view) {
this.model = model;
this.view = view;
}
public void SetProductName(string name) {
model.Name = name;
view.Update(model);
}
}
// View
public class ProductView {
public void Update(Product model) {
Console.WriteLine("Product name: " + model.Name);
}
}
Thus, MVC separates responsibilities, making it easier to maintain and develop the application.