public ActionResult Create()
 {
     var posts = new Posts();
     posts.category = new List<Category>();
     PopulateCategories(posts);
     return View();
 }
        private void PopulateCategories(Posts post)
        {
            var allCategories = db.Category;
            var assignedCategories = new HashSet<int>(post.category.Select(i => i.id));
            var viewModel = new List<linkedCategories>();

            foreach (var category in allCategories)
            {
                viewModel.Add(new linkedCategories
                {
                    id = category.id,
                    title = category.title,
                    linked = assignedCategories.Contains(category.id)
                });
            }
            ViewBag.Categories = viewModel;
        }
        public void updateCategories(string[] selectedCategories, Posts postToUpdate)
        {
            if (selectedCategories == null)
            {
                postToUpdate.category = new List<Category>();
                return;
            }

            var hsSelectedCategories = new HashSet<string>(selectedCategories);
            var postCategory = new HashSet<int>
                (postToUpdate.category.Select(i => i.id));
            foreach ( var category in db.Category)
            {
                if (hsSelectedCategories.Contains(category.id.ToString()))
                {
                    if (!postCategory.Contains(category.id))
                    {
                        postToUpdate.category.Add(category);
                    }
                }
                else
                {
                    if (postCategory.Contains(category.id))
                    {
                        postToUpdate.category.Remove(category);
                    }
                }
            }
        }