// GET: Create new Merchendiser
        public ActionResult Create()
        {
            Merchendiser merchendiser = new Merchendiser();
            merchendiser.Towns = new List<Town>();

            var townList = GetCheckedTownList(merchendiser);
            ViewBag.TownList = townList;

            return View("Edit", merchendiser);
        }
 public void UpdateMerchendiser(Merchendiser merchendiser)
 {
     db.Entry(merchendiser).State = System.Data.Entity.EntityState.Modified;
 }
 public void AddMerchendiser(Merchendiser merchendiser)
 {
     db.Merchendisers.Add(merchendiser);
 }
        // Update Merchendiser Town property with checked Towns from form
        private void UpdateMerchendisersTownList(Merchendiser merchToUpdate, string[] checkedTowns)
        {
            if (checkedTowns == null)
            {
                merchToUpdate.Towns = new List<Town>();
                return;
            }

            var checkedTownList = checkedTowns.ToList();
            var merchTowns = merchToUpdate.Towns.Select(t => t.TownId).ToList();

            foreach (Town t in repository.TownRepository.GetAllTowns())
            {
                if (checkedTownList.Contains(t.TownId.ToString()))
                {
                    if (!merchTowns.Contains(t.TownId))
                    {
                        merchToUpdate.Towns.Add(t);
                    }
                }
                else
                {
                    if (merchTowns.Contains(t.TownId))
                    {
                        merchToUpdate.Towns.Remove(t);
                    }
                }
            }
        }
        // get check towns for merchendisers from form and populate Towns property
        private void PopulateTownListForMerchendiser(Merchendiser merchendiser, string[] checkedTowns)
        {
            merchendiser.Towns = new List<Town>();

            if (checkedTowns != null)
            {
                foreach (string id in checkedTowns)
                {
                    Town town = repository.TownRepository.GetTownById(int.Parse(id));
                    merchendiser.Towns.Add(town);
                }
            }
        }
        // ***** METHODS ****** //
        // preparing for ListBox in view - Merchendisers towns
        // add evry town in list and check only ones that is in merchendisers town list
        private List<TownListViewModel> GetCheckedTownList(Merchendiser merchendiser)
        {
            List<TownListViewModel> townList = new List<TownListViewModel>();
            var merchTowns = merchendiser.Towns.Select(t => t.TownId);

            foreach (Town t in repository.TownRepository.GetAllTowns())
            {
                townList.Add(new TownListViewModel { TownId = t.TownId, TownName = t.TownName, IsChecked = merchTowns.Contains(t.TownId) });
            }

            return townList;
        }