1
votes

I'm having a hard time trying to work this out, how can I create a viewmodel with an interface,

I have been trying to follow a few examples online i.e

http://www.rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications

and

http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

But I just cannot get it to work, any help would be appreciated, my code so far is below.

public class TravelGuideViewModel
    {
    private readonly IGetCountryDetails _IGCD;
    public DisplayCountryDetails displayCountryDetails { get; set; }

    public TravelGuideViewModel(IGetCountryDetails IGCD)
        {
        _IGCD       = IGCD;
        }
    //Trying to get DisplayCountryDetails here, but everything i try does not work
    }

======================Update===============

public class TravelGuideViewModel
    {
    private readonly IGetCountryDetails _IGCD;
    public DisplayCountryDetails displayCountryDetails { get; set; }

    public TravelGuideViewModel(IGetCountryDetails IGCD)
        {
        _IGCD       = IGCD;
        }
    public TravelGuideViewModel Asia()
        {
        var countries = _IGCD.DisplayCountriesOfTheWorldDetails()
            .Where(a => a.strCountryContinent == "Asia").FirstOrDefault();

        return countries.strCountry.AsEnumerable(); << Does not work
        }
    }
1
its not very clear what you are attempting to accomplish. - Daniel A. White
I'm trying to create a viewmodel, but I have no idea how to, I see plenty of examples online but I cannot get any to work. Need to get data from DisplayCountryDetails into viewmodel and then pass data to view - CareerChange
It looks like you've got too much functionality in your model class - are you trying to inject a repository via the constructor? That should be in a controller or service class. - markpsmith

1 Answers

0
votes

The reason that your .AsEnumerable() does not work is because the return type on the function is TravelGuideViewModel not Enumerable.

Try something like...

public TravelGuideViewModel Asia()
{
  var countries = _IGCD.DisplayCountriesOfTheWorldDetails()
       .Where(a =>a.strCountryContinent == "Asia).FirstOrDefault();
      return new TravelGuideViewModel(countries);
}

In order to make something accessible to View, the ViewModel has to contain a pointer to it. Think of the ViewModel as the cup that your View is trying to drink out of. Not the drink itself. Handy to have, but not good for much if you do not fill it up with something.