rohit singh
rohit singh

Reputation: 1289

How can i fill a value from one my domain model to my edit model?

In my project i have : countries and CountryEditModel.

public class countries
{
     public int id { get; set; }
     public string Code { get; set; }
     public string Name { get; set; }
}

public class CountryEditModel
{
     public int id { get; set; }
     public string Code { get; set; }
     public string Name { get; set; }
     public bool isvalid{ get;set; }
}

countries is my domain model which is binded with entity framework and countryEditModel is the model which i use in my views.
How can i fill values from countries to countryEditModel. I actually want to bind list of all countries to dropdownlist in my view and I don't want to use my countries domain model directly in my view.

To solve i have done this

var countryDomain = context.Country.Select(c => c).ToList();
var countrylist = new List<CountryEditModel>();
var countrymodel = new CountryEditModel();
foreach (var country in countryDomain)
countrymodel = new CountryEditModel()
 {
   Code = country.Code,
   Name = country.Name,
   id = country.id
 };

countrylist.Add(countrymodel);

Is there any better way?

Answer:
Actually this is what i exactly wanted to do

 var countryViewModel = context.Country.Select(c => new CountryEditModel
                {
                    Code = c.Code,
                    Name = c.Name,
                    id = c.id
                }).ToList();

Upvotes: 0

Views: 94

Answers (1)

jessehouwing
jessehouwing

Reputation: 114751

As indicated by the @rohitsingh this is what he exactly wanted to do

var countryViewModel = context.Country.Select(c => new CountryEditModel
    {
        Code = c.Code,
        Name = c.Name,
        id = c.id
    }).ToList();

Upvotes: 1

Related Questions