Defining view models for MVC / MVP

后端 未结 3 1904
陌清茗
陌清茗 2021-01-17 00:18

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 wi
3条回答
  •  不思量自难忘°
    2021-01-17 00:49

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

    
    
    

    Our foo:
    ${Html.DisplayFor(x=>x.foo)}

    Our fizz:
    ${Html.DisplayFor(x=>x.fizz)}

    ${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.

提交回复
热议问题