Mahdi GB
Mahdi GB

Reputation: 65

How to send model data to a view through a controller in MVC C#

I have already seen a lot of different MVC architectures. All of them are different. I would like to know a standard way to send a model data to a view using a controller. Is it suitable to send the model object to the view and set view fields using one setter? or set the view fields one by one using several setters with one parameter or other way?

public class View{
    public void SetField1(int value){
      //...
    }
    public void SetField2(string text){
      //...
    }
    public void SetField3(Time time){
      //...
    }
    //or
    public void SetContent(Model model){
       //...
    }
}

public class Model{
   public int _value;
   public string _text;
   public Time _time;

   public Model(int value,string text,Time time){
     //...
   }
}

public class Controller{
   Model _model;
   View _view;

   public Controller(){
      _model=new Model();
      _view=new View();
   }
   public void SetModel(Model model){
      _model=model;
      SetContentView();
   }
   public void SetView(View view){
      _view=view;
   }
   public void SetContentView(){
      _view.SetField1(_model._value);
      _view.SetField2(_model._text);
      _view.SetField3(_model._time);
      //or
      _view.SetContent(_model); // the view can not be decoupled with model!
   }
} 

Upvotes: 0

Views: 946

Answers (1)

zaq
zaq

Reputation: 2661

You could create a ModelView object that explicitly defines the properties needed by your view. Then you could define a Mapper class responsible for mapping the server side model into the client side model, thus decoupling the view from the server's model.

From your example:

public class Controller{
   Model _model;
   View _view;
   Mapper _mapper;

   public Controller(){
      _model=new Model();
      _view=new View();
      _mapper = new ViewModelMapper();

   }

   public void SetContentView(){
      _view.SetContent(_mapper.map(_model));
   }
} 

I don't have much experience with them, but there do exist frameworks intended to make this less tedious: http://automapper.org/

Upvotes: 1

Related Questions