asp.net-mvcarchitecturemvp

Defining view models for MVC / MVP


Short question - how do you define your view models?

Here are some of the options:

  1. Pass the actual model into the view.
  2. Create a view model with a reference to the model (like Model.Product)
  3. Create a view model with the properties needed from the model, and set those from the model.
  4. Probably a lot more.

All with their own advantages and disadvantages.

What is your experience - good and bad? And do you use the same model for GET/POST?

Thanks for your input!


Solution

  • Basically - it's all about separating responsibilities.

    More you separate them - more verbose, complex but easier to understand it gets.


    Model:

    public class foo{
        string Name{get;set}
        Bar Bar {get;set;}
        string SomethingThatIsUneccessaryInViews {get;set;}
    }
    
    public class bar{
        string Name {get;set;}
    }
    
    public class fizz{
        string Name{get;set;}
    }
    

    Presenter (i admit - still haven't got idea of MVP completely):

    public someSpecificViewPresenter{
        fizz fizz{get;set;}
        foo foo{get;set;}
        necessaryThingsForWhatever[] necessaryThingsForWhatever{get;set;}
        public void someLogicIfNeeded(){...}        
    }
    

    magic object2object mapping & flattening, viewmodel modelmetadata configuration goes here...

    ViewModel (NB=>POCOS with container props only. No logic should go here.):

    public class fooViewModel{
        string Name {get;set;}
        string BarName {get;set;}
    }
    
    public class fizzViewModel{
        string Name {get;set;}
    }
    
    public class someSpecificView{
        fooViewModel foo {get;set;}
        fizzViewModel fizz {get;set;}
        whateverViewModel whatever {get;set;}
    }
    

    and here goes "das happy ending"...

    <use viewdata="someSpecificView m" />
    
    <p>
    Our foo:<br/>
    ${Html.DisplayFor(x=>x.foo)}
    </p>
    
    <p>
    Our fizz:<br/>
    ${Html.DisplayFor(x=>x.fizz)}
    </p>
    
    ${Html.UberPaging(m.whatever.Paging)}
    

    And yes, i use same model for GET/POST. See this for more why/ifs.


    But lately - I'm looking for other solutions. CQRS buzz catch my eye.