public JsonResult Save(SaveLandlordTemplatesRequest request) { List<int> UsedAreas = new List<int>(); List<int> UsedItems = new List<int>(); if (request.Areas != null) { foreach (var requestArea in request.Areas) { LandlordTemplateArea area = db.LandlordTemplateAreas.Where(x => x.AreaName.ToLower() == requestArea.AreaName.ToLower()).FirstOrDefault(); ; bool newArea = false; if (area == null) { area = new LandlordTemplateArea(); newArea = true; } area.AreaName = requestArea.AreaName; area.AreaOrder = requestArea.AreaOrder; if (newArea) db.LandlordTemplateAreas.Add(area); db.SaveChanges(); UsedAreas.Add(area.LandlordTemplateAreaID); if (requestArea.Items != null) { foreach (var itemRequest in requestArea.Items) { LandlordTemplateAreaItem item = db.LandlordTemplateAreaItems.Where(x => x.LandlordTemplateAreaID == area.LandlordTemplateAreaID && x.ItemName == itemRequest.ItemName).FirstOrDefault(); bool newItem = false; if (item == null) { item = new LandlordTemplateAreaItem(); newItem = true; } item.ItemName = itemRequest.ItemName; item.ItemOrder = itemRequest.ItemOrder; item.LandlordTemplateAreaID = area.LandlordTemplateAreaID; if (newItem) db.LandlordTemplateAreaItems.Add(item); db.SaveChanges(); UsedItems.Add(item.LandlordTemplateAreaItemID); } } } } db.LandlordTemplateAreas.RemoveRange(db.LandlordTemplateAreas.Where(x => !UsedAreas.Contains(x.LandlordTemplateAreaID)).ToList()); db.LandlordTemplateAreaItems.RemoveRange(db.LandlordTemplateAreaItems.Where(x => !UsedItems.Contains(x.LandlordTemplateAreaItemID)).ToList()); db.SaveChanges(); return Json(true); }
public JsonResult Save(List<LandlordTemplateArea> areas) { SaveLandlordTemplatesRequest request = new SaveLandlordTemplatesRequest(); request.Areas = new List<CreateLandlordTemplateAreaRequest>(); if (areas != null) { foreach (var area in areas) { CreateLandlordTemplateAreaRequest areaRequest = new CreateLandlordTemplateAreaRequest(); areaRequest.AreaName = area.Name; areaRequest.AreaOrder = area.Order; areaRequest.Items = new List<CreateLandlordTemplateAreaItemRequest>(); if (area.Items != null) { foreach (var item in area.Items) { CreateLandlordTemplateAreaItemRequest itemRequest = new CreateLandlordTemplateAreaItemRequest(); itemRequest.ItemName = item.Name; itemRequest.ItemOrder = item.Order; areaRequest.Items.Add(itemRequest); } } request.Areas.Add(areaRequest); } } var response = ApiWrapper.Post<bool>("api/save-templates", request); return Json(true); }