示例#1
0
        public ActionResult Edit(SnippetCRUDViewModel model)
        {
            if (ModelState.IsValid && !string.IsNullOrEmpty(model.Snippet.Name) && !string.IsNullOrEmpty(model.Snippet.Code))
            {
                //model.Snippet.LanguageId = model.SelectedLanguageId;
                var language = _langRepo.Languages.FirstOrDefault(l => l.LanguageId == model.SelectedLanguageId);
                var user     = _userRepo.Users.FirstOrDefault(u => u.Username == User.Identity.Name);

                if (user != null)
                {
                    model.Snippet.UserId = user.UserId;
                }

                if (language != null)
                {
                    model.Snippet.LanguageId = language.LanguageId;
                }
                model.Snippet.Groups.Clear();
                _snipRepo.SaveSnippet(model.Snippet);

                //Add it to the groups
                if (model.SelectedGroupId != null)
                {
                    _groupRepo.UpdateGroupsWithSnippet(model.SelectedGroupId, model.Snippet);
                }


                TempData["message"] = string.Format("{0} has been saved!", model.Snippet.Name);
                return(RedirectToAction("List"));
            }

            //An error occured, find out what's missing
            if (string.IsNullOrEmpty(model.Snippet.Name))
            {
                ModelState.AddModelError("Snippet.Name", "Name is required!");
            }
            if (string.IsNullOrEmpty(model.Snippet.Code))
            {
                ModelState.AddModelError("Snippet.Code", "No empty snippets allowed!");
            }

            //Add model languages and group options again
            var groupSL = new List <SelectListItem>();

            groupSL.Add(new SelectListItem
            {
                Text  = "None",
                Value = "-1"
            });
            groupSL.AddRange(_groupRepo.GetGroupsForUsername(User.Identity.Name)
                             .Select(g => new SelectListItem
            {
                Text  = g.Name,
                Value = g.Id.ToString()
            })
                             .ToList());
            model.Groups    = groupSL;
            model.Languages = _langRepo.LangOptions;

            return(View(model));
        }