Beispiel #1
0
        public async Task <IActionResult> Save(DeviceViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Form", model));
            }

            try
            {
                if (string.IsNullOrWhiteSpace(model.Id))
                {
                    // Insert
                    var entry = _mapper.Map <Device>(model);
                    await _devices.InsertOneAsync(entry);

                    model.Id = entry.Id;
                }
                else
                {
                    // Update
                    var entry = await _devices.GetFirstOrDefaultAsync(a => a.Id == model.Id);

                    if (entry == null)
                    {
                        return(NotFound());
                    }

                    _mapper.Map(model, entry);
                    var result = await _devices.ReplaceOneAsync(a => a.Id == model.Id, entry);

                    if (result.MatchedCount != 1)
                    {
                        return(NotFound());
                    }
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.Message);
                return(View("Form", model));
            }

            return(RedirectToAction("List"));
        }