Пример #1
0
        public async Task<IHttpActionResult> Create (Blogpost model)
        {
            var cats = db.Categories;

            if(!cats.Any(c=> c.Name == model.Category.Name) || cats == null)
            {
                var newCat = new Category()
                {
                    Name = model.Category.Name
                };

                db.Categories.Add(newCat);
                await db.SaveChangesAsync();
                model.Category.Id = newCat.Id;
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var slug = StringUtilities.UrlFriendly(model.Title);

            if (String.IsNullOrWhiteSpace(slug))
            {
                ModelState.AddModelError("Title", "Invalid Title");
                return BadRequest(ModelState);
            }

            if(db.Posts.Any(p=> p.Slug == slug))
            {
                ModelState.AddModelError("Title", "The title must be unique.");
                return BadRequest(ModelState);
            }
            else
            {
                model.Slug = slug;
                model.Created = DateTimeOffset.UtcNow;
                model.CategoryId = model.Category.Id;
                model.Category = null;
                model.AuthorName = db.Users.Find(User.Identity.GetUserId()).DisplayName;
                db.Posts.Add(model);
                await db.SaveChangesAsync();

                return Ok();
            }



            
        }
Пример #2
0
        public async Task<IHttpActionResult> Edit (Blogpost model)
        {
            var cats = db.Categories;

            if(!cats.Any(c=> c.Name == model.Category.Name))
            {
                var newCat = new Category()
                {
                    Name = model.Category.Name
                };
                db.Categories.Add(newCat);
                await db.SaveChangesAsync();
                model.Category.Id = newCat.Id;
            }
            else
            {
                model.Category.Id = model.Category.Id;
                model.Category = null;
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            model.Updated = DateTimeOffset.UtcNow;
            db.Entry(model).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return Ok();
        }