c# - Which one should I use for Create page : Model or ViewModel? -


i have following entities , viewmodel (some properties removed clarity):

ticket:

public class ticket {     [key]      public int id { get; set; }      public string comment { get; set; }      //navigation property     public virtual icollection<attachment> attachments { get; set; } } 


attachment:

public class attachment {     [key]     public int id { get; set; }      //foreign key ticket     public int ticketid { get; set; }      public byte[] filedata { get; set; }      public string filemimetype { get; set; }      //navigation property      public virtual ticket ticket { get; set; } } 


ticketviewmodel:

public class ticketviewmodel {     //default constructor     public ticketviewmodel()     {      }       //constructor parameter     public ticketviewmodel(ticket ticket)     {         ticket = ticket;         attachment = new attachment();     }      public ticket ticket { get; set; }      public attachment attachment { get; set; }        public virtual icollection<attachment> attachments { get; set; }               } 


in create new ticket page, there attachment field , multiple attachments can added newly created ticket. reason use ticketviewmodel , pass ticket , icollection<attachment> controller. on other hand, not sure if wrong, because can pass 'ticket' controller , create new instance of ticketviewmodel in controller passing ticket model constructor of ticketviewmodel. in scenario, approach should follow?
note: pass ienumerable<httppostedfilebase> controller attachment data.


update:

i updated view , pass model instead of viewmodel shown below:

view:

@model ticket //... other stuff 

and in controller, pass filled model , new instance of attachment collection method in data layer shown below.


controller:

list<fileattachment> fa = new list<fileattachment>(); 

while real answer subjective , based entirely on personal preference, give answer , reasons.

passing so-called view model typically better passing entity poco, due fact page/forms require more data used in poco.

in case provided flatten classes in view model merging properties 1 class easy binding, , create process() function provide 2 pocos needed. when working complex models process() function return new domain model save, or accept domain model edit.

for example, may want provide cheap bot protection in form of arithmetic problem wouldn't need saved anywhere. passing view model can limit exposing of data, in case person doing end stuff different person laying out views.

in cases, though, poco can fine. tend pass view models complex data, , actual poco small tables, when 2 columns uid , text field.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -