c# - ViewModel MVC 5 2 models, db, controller view relationship understanding -


i keep trying head around whole concept , use guys. i'm working code first approach. made post yesterday here further work based on advises didn't work me. make problem clear go on again.

i have 2 simple classes.

 public class media     {         public int id { get; set; }         public string title { get; set; }          public string description { get; set; }         public string body { get; set; }         public string imagepath { get; set; }             } 

and

public class video {     public int id { get; set; }     public string title { get; set; }     public string description { get; set; }     public string videolink { get; set; }     public string tags { get; set; } } 

for each of them have own controller , set of crud views genereated ef. can create , store 2 objects in db, have context class that:

public class eventscontext : dbcontext     {         public dbset<media> medias { get; set; }         public dbset<video> videos { get; set; }         }        } 

i have method im mediascontroller

public actionresult mediamain() {     ienumerable<media> medias = db.medias;     viewbag.medias = medias;     return view(); } 

it accesses stored object db , allows work every field in view. way.

@foreach (var b in viewbag.model) {     @html.raw(model.imagepath) } 

good , sound, understand that. but. still have 2 different views, while need one. created mediaviewmodel class (thanks that) looking this:

public class mediaviewmodel {     public media media { get; set; }     public video video { get; set; } } 

if create method in mediascontroller looks this:

public actionresult mediamain () {     var model = new mediaviewmodel();     return view(model); } 

i cant access data objects, gives me nullexception, looks i'm not sending on object. think need have ienumerable<mediaviewmodel> medias = db.mediaviewmodel; don't have in db context, need create one? if so, collection of object of 2 classes? that's not sound right. need see happening in controller , in view able access data need. pls help.

your model

public class mediaviewmodel {     public list<media> media { get; set; }     public list<video> video { get; set; } } 

your controller method:

public actionresult mediamain () {     var model = new mediaviewmodel();     model.media = db.medias.tolist();     model.video = db.videos.tolist();     return view(model); } 

hope helps.


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -