0

I have a view-model like this:

public class U1MyProfile1ViewModel : U1Profile
{
    public List<SelectListItem> CountryList { get; set; }
}

Thinking that I want the model accessible to the view, plus a some extra fields that aren't really part of the model, such as a drop down list of countries.

Then in the controller I try to "pass the model over to the view-model"

        var myProfile = await _mainDbContext.U1Profiles
            .AsNoTracking()
            .FirstOrDefaultAsync(i => i.SiteUserId == mySiteUserId);

        U1MyProfile1ViewModel myProfileViewModel = (U1MyProfile1ViewModel)myProfile; 

this compiles, but I get a runtime error of:

InvalidCastException: Unable to cast object of type 'WebApp.Models.U1Profile' to type 'WebApp.ViewModels.U1MyProfile1ViewModel'.

Any ideas on how to do this easily?
Something simpler than assigning the model to the view-model field by field.

Llazar
  • 3,167
  • 3
  • 17
  • 24
user2328625
  • 361
  • 4
  • 13
  • If you do not want to initialize and map `U1Profile` to `U1MyProfile1ViewModel`, then you can consider using [AutoMapper](https://automapper.org/) - but you would still need to populate the SelectList –  Oct 29 '18 at 04:38
  • 1
    Why you inherits viewmodel to model? View model is always work freely without depending on anything. – Kiran Joshi Oct 29 '18 at 06:16

1 Answers1

1

Set your View model like follow:

View modal

public class U1MyProfile1ViewModel
{
    public List<SelectListItem> CountryList { get; set; }
    public U1Profile U1Profile{get;set;}
    public string othervariable{get;set;}
}

Controller

var myProfile = await _mainDbContext.U1Profiles
            .AsNoTracking()
            .FirstOrDefaultAsync(i => i.SiteUserId == mySiteUserId);

        U1MyProfile1ViewModel myProfileViewModel = new U1MyProfile1ViewModel;
       U1MyProfile1ViewModel.U1Profile=myProfile;
       U1MyProfile1ViewModel.CountryList=yourcountrylist;

And finally just passed your viewmodal to View and you get your result.

For better understanding just see below link:
Link1
Link2

Kiran Joshi
  • 1,758
  • 2
  • 11
  • 34
  • View model should not contain data models when editing data - it defeats the whole point of using view model (separation of concerns, protection against over-posting attacks, protection against under-posting attacks etc) –  Oct 29 '18 at 07:42
  • @StephenMuecke make sense. Thanks. How we deal with this ? – Kiran Joshi Oct 30 '18 at 04:49