public ActionResult AddAndRenderListDetallesOrden(IList <string> jsonDetallesList, Guid?assetId, string nameAsset, double?stockAsset, double?price) { try { IEnumerable <DetailAssetAdjustmentDto> detalleList = new JavaScriptSerializer().Deserialize <IList <DetailAssetAdjustmentDto> >(jsonDetallesList[0]); if (assetId == null) { return(Json(new { Error = -1, Message = "Por Favor seleccione el artículo correctamente." })); } if (stockAsset == null || stockAsset < 0) { return(Json(new { Error = -1, Message = "Por Favor indique la cantidad del artículo correctamente." })); } if (price == null || price < 0) { return(Json(new { Error = -1, Message = "Por Favor indique el precio de costo del artículo correctamente." })); } if (detalleList.Any(item => item.AssetId == assetId && item.Delete == 0)) { return(Json(new { Error = -1, Message = "Ya existe una salida para el artículo" + nameAsset + " por favor edite correctamente el detalle." })); } DetailAssetAdjustmentDto detalle = new DetailAssetAdjustmentDto(); detalle.AssetId = (Guid)assetId; detalle.NameAsset = nameAsset; if (stockAsset > 0.0) { detalle.StockAsset = (double)stockAsset; } else { return(Json(new { Error = -1, Message = "Por Favor indique la cantidad del artículo correctamente." })); } detalle.Price = (double)price; detalle.Saved = 0; detalle.Update = 1; detalle.Delete = 0; detalle.ErrorDescription = ""; detalle.ErrorCode = 0; IList <DetailAssetAdjustmentDto> newList = new List <DetailAssetAdjustmentDto>(); int index = 0; foreach (var item in detalleList) { item.Index = index; newList.Add(item); index++; } detalle.Index = index; newList.Add(detalle); return(PartialView("_tableDetails", newList)); } catch (Exception) { return(Json(new { Error = -1, Message = "Error al Agregar/Modificar la Solicitud" })); } }
public PartialViewResult CheckOutOrder() { var codeCookie = HttpContext.Request.Cookies["addtocart"]; var list = new List <ShopProductCartItem>(); if (codeCookie != null) { var temp = codeCookie.Value; var lst = new JavaScriptSerializer().Deserialize <List <ShopProductDetailCartItem> >(temp); if (lst.Any()) { list = (from item in lst let model = _productDa.GetProductCart(item.ProductId ?? 0, item.SizeID ?? 0) where model != null select new ShopProductCartItem { Name = model.Name, ColorName = model.ColorName, ColorCode = model.ColorCode, UrlPicture = model.UrlPicture, ID = model.ID, Price = model.Price, Total = model.Price * item.Quantity, Quantity = item.Quantity, ProductId = item.ProductId, SizeId = item.SizeID, ShopID = item.ShopID }).ToList(); } } return(PartialView(list)); }
public void Test_Buy_Item_Until_Deplete_The_Stock() { var result = GetInventory(null); var items = new JavaScriptSerializer().Deserialize <IEnumerable <Item> >(result.Item1); Assert.IsNotNull(items); Assert.IsTrue(items.Any()); var firstItemWithLargeStock = items.OrderByDescending(itm => itm.Quantity).FirstOrDefault(itm => itm.Quantity > 0 && itm.Quantity < 20); Assert.IsNotNull(firstItemWithLargeStock); Assert.IsNotNull(token.access_token); //Act for (int i = 0; i < firstItemWithLargeStock.Quantity; i++) { var resultPurchaseAttempt = BuyItem(firstItemWithLargeStock.Id, token); //assert that the purchase succeeded Assert.IsNotNull(resultPurchaseAttempt); Assert.AreEqual(resultPurchaseAttempt.Item2, HttpStatusCode.OK); Assert.IsTrue(resultPurchaseAttempt.Item1.Equals("true", StringComparison.OrdinalIgnoreCase)); } //Act var depletedStockPurchaseAttempt = BuyItem(firstItemWithLargeStock.Id, token); //Assert that the last buy attempt failed due to stock depletion Assert.IsNotNull(depletedStockPurchaseAttempt); Assert.AreEqual(depletedStockPurchaseAttempt.Item2, HttpStatusCode.OK); Assert.IsTrue(depletedStockPurchaseAttempt.Item1.Equals("false", StringComparison.OrdinalIgnoreCase)); }
/// <summary> /// 更新期初数 /// </summary> /// <param name="data"></param> /// <returns></returns> public string UpdBeginningBalance(string data) { string strFmt = "{{\"Result\":{0},\"Msg\":\"{1}\"}}"; string msg = string.Empty; List <T_BeginningBalance> beginningBalance = new JavaScriptSerializer().Deserialize <List <T_BeginningBalance> >(data); T_BeginningBalance currItem = new T_BeginningBalance(); while (beginningBalance.Any(i => i.children.Count > 0)) { currItem = beginningBalance.Where(i => i.children.Count > 0).FirstOrDefault(); beginningBalance.AddRange(currItem.children); currItem.children = new List <T_BeginningBalance>(); } bool result = false; if (true) { result = new ReportSvc().UpdBeginningBalance(beginningBalance, Session["CurrentCompanyGuid"].ToString()); msg = result ? General.Resource.Common.Success : General.Resource.Common.Failed; } else { msg = FMS.Resource.FinanceReport.FinanceReport.VaildError; } return(string.Format(strFmt, result.ToString().ToLower(), msg)); }
public void Test_Buy_An_Item_Until_The_Stock_Is_Depleted() { //Arrange Assert.IsNotNull(token); Assert.IsFalse(string.IsNullOrEmpty(token.access_token)); var result = GetInventory(token); Assert.IsFalse(string.IsNullOrEmpty(result.Item1)); var items = new JavaScriptSerializer().Deserialize <IEnumerable <Item> >(result.Item1); Assert.IsNotNull(items); Assert.IsTrue(items.Any()); var firstItem = items.OrderBy(itm => itm.Quantity).First(); //Act //buy all the stock for (int i = 0; i < firstItem.Quantity; i++) { result = BuyItem(token, firstItem.Id); //Assert that the item was bought Assert.IsTrue(result.Item1.Equals("true", StringComparison.OrdinalIgnoreCase)); } result = BuyItem(token, firstItem.Id); //Assert that you cannot buy this item Assert.IsTrue(result.Item1.Equals("false", StringComparison.OrdinalIgnoreCase)); }
public void Test_GetInventory_With_NoAuth() { //Act var result = GetInventory(null); var items = new JavaScriptSerializer().Deserialize <IEnumerable <Item> >(result.Item1); //Assert that you get inventory items Assert.IsNotNull(items); Assert.IsTrue(items.Any()); }
public static bool IsAuthenticated(string userName, string password) { bool isAuthenticated = false; string json = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/Users.txt")); var users = new JavaScriptSerializer().Deserialize <List <User> >(json); isAuthenticated = users.Any(u => u.UserName == userName && u.Password == password); return(isAuthenticated); }
private async Task EnsurePostIsDeleted(HttpClient httpClient, int newPostId) { var listResult2 = await httpClient.GetAsync(createPostUri); Assert.AreEqual(HttpStatusCode.OK, listResult2.StatusCode, "GET API method failed"); var listItems2 = new JavaScriptSerializer().Deserialize <List <PostListItemModel> >(listResult2.Content.ReadAsStringAsync().Result); Assert.IsFalse(listItems2.Any(p => p.Id == newPostId)); }
public void Test_GetInventory_With_NoAuth() { //Act var result = GetInventory(null);//no auth //Assert Assert.IsFalse(string.IsNullOrEmpty(result.Item1)); var items = new JavaScriptSerializer().Deserialize <IEnumerable <Item> >(result.Item1); Assert.IsNotNull(items); Assert.IsTrue(items.Any()); }
public void Test_Buy_Item_WithNoAuth() { //Arrange var result = GetInventory(null); var items = new JavaScriptSerializer().Deserialize <IEnumerable <Item> >(result.Item1); Assert.IsNotNull(items); Assert.IsTrue(items.Any()); var firstItemWithStock = items.FirstOrDefault(itm => itm.Quantity > 0); Assert.IsNotNull(firstItemWithStock); //Act var resultPurchaseAttempt = BuyItem(firstItemWithStock.Id, null); //Assert that the purchase failed because the lack of Authentication Assert.IsNotNull(resultPurchaseAttempt); Assert.AreEqual(resultPurchaseAttempt.Item2, HttpStatusCode.Unauthorized); }
public JsonResult SendList(PersonModel n) { if (n != null && !string.IsNullOrWhiteSpace(n.Name)) { // get from DB string result = string.Empty; var rr = new JavaScriptSerializer().Deserialize <string[]>("[\"omid\",\"arthur\",\"arthur2\",\"cécile\"]"); rr = rr.Where(k => k.ToLower().Contains(n.Name.ToLower())).ToArray(); if (rr == null || !rr.Any()) { return(Json("No data found")); } return(Json(rr)); } return(Json("An error accured")); }
public ActionResult AddAndRenderListDetallesOrden(IList <string> jsonDetallesList, int?idNumero, int?numero, int?montoApuesta) { try { IEnumerable <DetalleApuestaViewModel> detalleList = new JavaScriptSerializer().Deserialize <IList <DetalleApuestaViewModel> >(jsonDetallesList[0]); if (detalleList.Any(item => item.IdNumero == idNumero)) { return(Json(new { Error = -1, Message = "Ya existe una entrada para el numero " + numero + " por favor ingrese correctamente la apuesta." })); } if (montoApuesta == null || montoApuesta <= 0) { return(Json(new { Error = -1, Message = "Por Favor indique monto correctamente." })); } DetalleApuestaViewModel detalle = new DetalleApuestaViewModel(); detalle.IdNumero = (int)idNumero; detalle.Numeros = (int)numero; detalle.Monto = (int)montoApuesta; detalle.Borrar = 0; detalle.ErrorDescription = ""; detalle.ErrorCode = 0; //Agregamos a la lista IList <DetalleApuestaViewModel> newList = new List <DetalleApuestaViewModel>(); int index = 0; foreach (var item in detalleList) { newList.Add(item); index++; } newList.Add(detalle); return(PartialView("_detalleApuestas", newList)); } catch (Exception) { return(Json(new { Error = -1, Message = "Error al Agregar la Apuesta" })); } }
public void Test_Attempt_BuyItem_With_NoAuth() { //Act var result = GetInventory(null);//no auth //Assert Assert.IsFalse(string.IsNullOrEmpty(result.Item1)); var items = new JavaScriptSerializer().Deserialize <IEnumerable <Item> >(result.Item1); Assert.IsNotNull(items); Assert.IsTrue(items.Any()); var firstItem = items.OrderBy(itm => itm.Quantity).First(); //Act result = BuyItem(null, firstItem.Id); //Assert Assert.IsNotNull(result); Assert.AreEqual(result.Item2, System.Net.HttpStatusCode.Unauthorized); }
public void GetCitiesTest() { var connectionString = GetConnectionString(); var url = GetBaseUrl() + "/api/cities"; var r = Get(url); var list = new JavaScriptSerializer().Deserialize <List <City> >(r); using (var context = new RaterPriceContext()) { var cities = context.Cities.Select(c => c); Assert.AreEqual(list.Count(), cities.Count()); foreach (var c in cities) { var id = c.Id; var name = c.Name; Assert.AreEqual(list.Any(x => x.Name == name && x.Id == id), true); } } }
public List <ElmahError> GetElmahError(DateTime start, DateTime end) { if (StorageAccount == null) { StorageAccount = CloudStorageAccount.Parse(ConnectionString); } List <string> nonCriticalErrorDictionary = new JavaScriptSerializer().Deserialize <List <string> >(Load(StorageAccount, "Configuration.ElmahNonCriticalErrors.json", ContainerName)); TableErrorLog log = new TableErrorLog(string.Format(ElmahAccountCredentials)); List <ErrorLogEntry> entities = new List <ErrorLogEntry>(); int lasthours = DateTime.Now.Subtract(start).Hours + 1; log.GetErrors(0, 500 * lasthours, entities); //retrieve n * LastNHours errors assuming a max of 500 errors per hour. List <ElmahError> listOfErrors = new List <ElmahError>(); //Get the error from Last N hours. if (entities.Any(entity => entity.Error.Time.ToUniversalTime() > start.ToUniversalTime() && entity.Error.Time.ToUniversalTime() < end.ToUniversalTime())) { entities = entities.Where(entity => entity.Error.Time.ToUniversalTime() > start.ToUniversalTime() && entity.Error.Time.ToUniversalTime() < end.ToUniversalTime()).ToList(); var elmahGroups = entities.GroupBy(item => item.Error.Message); //Group the error based on exception and send alerts if critical errors exceed the thresold values. foreach (IGrouping <string, ErrorLogEntry> errorGroups in elmahGroups) { Console.WriteLine(errorGroups.Key.ToString() + " " + errorGroups.Count()); int severity = 0; if (nonCriticalErrorDictionary.Any(item => errorGroups.Key.ToString().Contains(item))) { severity = 1; //sev 1 is low pri and sev 0 is high pri. } string link = "https://www.nuget.org/Admin/Errors.axd/detail?id={0}"; if (ContainerName.Contains("qa")) { link = "https://int.nugettest.org/Admin/Errors.axd/detail?id={0}"; } //for severity, assume all refresh error, severity = 0 listOfErrors.Add(new ElmahError(errorGroups.Key.ToString(), errorGroups.Count(), errorGroups.Min(item => item.Error.Time.ToLocalTime()), errorGroups.Max(item => item.Error.Time.ToLocalTime()), string.Format(link, errorGroups.First().Id), errorGroups.First().Error.Detail, severity)); } } return(listOfErrors); }
public ActionResult UpdateCart(int productId, int type, int quantity = 0) { var msg = new JsonMessage(); var codeCookie = HttpContext.Request.Cookies["addtocart"]; if (codeCookie != null) { var temp = codeCookie.Value; var lst = new JavaScriptSerializer().Deserialize <List <ShopProductDetailCartItem> >(temp); var check = lst.Any(c => c.ShopID == productId); if (check) { switch (type) { case 1: foreach (var item in lst.Where(item => item.ShopID == productId)) { item.Quantity = quantity; break; } break; case 2: var itemremove = lst.SingleOrDefault(item => item.ShopID == productId); if (itemremove != null) { lst.Remove(itemremove); } break; } var val = new JavaScriptSerializer().Serialize(lst); codeCookie = new HttpCookie("addtocart") { Value = val, Expires = DateTime.Now.AddHours(6) }; Response.Cookies.Add(codeCookie); } } return(Json(msg, JsonRequestBehavior.AllowGet)); }
public virtual ActionResult AddToCompareList(long?productId) { if (productId == null) { return(Content(null)); } var itemsInCookie = new List <ProductCompareViewModel>(); var cookieValue = HttpContext.GetCookieValue(TotalInCompareCookieName); var count = string.IsNullOrEmpty(cookieValue) ? 0 : int.Parse(cookieValue); if (count > 5) { return(Content("limit")); } var product = _productService.GetForAddToCompare(productId.Value); if (count == 0) { HttpContext.AddCookie(TotalInCompareCookieName, (++count).ToString(), DateTime.Now.AddDays(1)); } else { itemsInCookie = new JavaScriptSerializer().Deserialize <List <ProductCompareViewModel> >( HttpContext.GetCookieValue(CompareListCookieName)); if (itemsInCookie.Any(a => a.ProductId == productId.Value)) { return(Content("nok")); } if (itemsInCookie.Count > 4) { return(Content("limit")); } HttpContext.UpdateCookie(TotalInCompareCookieName, (++count).ToString()); } itemsInCookie.Add(product); HttpContext.UpdateCookie(CompareListCookieName, itemsInCookie.ToJson()); return(Content("ok")); }
public void GetShopsTest() { var connectionString = GetConnectionString(); const int cityId = 8; const string querySearch = "О"; var url = GetBaseUrl() + $"api/shops/search?cityId={cityId}&querySearch={querySearch}"; var r = Get(url); var list = new JavaScriptSerializer().Deserialize <List <Shop> >(r); using (RaterPriceContext context = RaterPriceContext.Create()) { var shops = context.Shops.Where(s => s.CityId == cityId && s.Name.IndexOf(querySearch) > -1).Select(s => s); Assert.AreEqual(list.Count(), shops.Count()); foreach (var s in shops) { var shopId = s.Id; var shopCityId = s.CityId; var shopName = s.Name; Assert.AreEqual(list.Any(x => x.Name == shopName && x.Id == shopId && x.CityId == shopCityId), true); } } }
public ActionResult Addtocart(int productId, int quantity, int shopId, int sizeId = 0) { var msg = new JsonMessage { Erros = false, Message = "Bạn đã thêm sản phẩm vào giỏ hàng" }; if (quantity <= 0) { msg = new JsonMessage { Erros = true, Message = "Số lượng phải >= 1.", }; return(Json(msg, JsonRequestBehavior.AllowGet)); } if (shopId == 0) { msg = new JsonMessage { Erros = true, Message = "Không thể đặt sản phẩm này.", }; return(Json(msg, JsonRequestBehavior.AllowGet)); } var obj = new List <ShopProductDetailCartItem>(); var codeCookie = HttpContext.Request.Cookies["addtocart"]; if (codeCookie == null) { var item = new ShopProductDetailCartItem { ProductId = productId, SizeID = sizeId, Quantity = quantity, ShopID = shopId, }; obj.Add(item); var val = new JavaScriptSerializer().Serialize(obj); codeCookie = new HttpCookie("addtocart") { Value = val, Expires = DateTime.Now.AddHours(6) }; Response.Cookies.Add(codeCookie); } else { var temp = codeCookie.Value; var lst = new JavaScriptSerializer().Deserialize <List <ShopProductDetailCartItem> >(temp); var check = lst.Any(c => c.ProductId == productId && c.SizeID == sizeId); if (check) { foreach (var item in lst.Where(item => item.ProductId == productId && item.SizeID == sizeId)) { item.Quantity = (item.Quantity ?? 0) + quantity; item.ShopID = shopId; break; } var val = new JavaScriptSerializer().Serialize(lst); codeCookie = new HttpCookie("addtocart") { Value = val, Expires = DateTime.Now.AddHours(6) }; Response.Cookies.Add(codeCookie); } else { var item = new ShopProductDetailCartItem { ProductId = productId, SizeID = sizeId, Quantity = quantity, ShopID = shopId, }; lst.Add(item); var val = new JavaScriptSerializer().Serialize(lst); codeCookie = new HttpCookie("addtocart") { Value = val, Expires = DateTime.Now.AddHours(6) }; Response.Cookies.Add(codeCookie); } //codeCookie.Value = val; codeCookie.Expires = DateTime.Now.AddHours(6); Response.Cookies.Add(codeCookie); } return(Json(msg, JsonRequestBehavior.AllowGet)); }
public async Task IntegrationAllPostMethods() { using (var httpClient = new HttpClient()) { var newPost = new { Title = "SampleTitle", Content = "SampleContent" }; // New post creation test var postResult = await httpClient.PostAsJsonAsync(ApiAction("Post"), newPost); Assert.AreEqual(HttpStatusCode.OK, postResult.StatusCode, "POST API method failed"); var newPostId = int.Parse(postResult.Content.ReadAsStringAsync().Result); Assert.IsTrue(newPostId > 0); // Load newly created post test var getResult = await httpClient.GetAsync(ApiAction(string.Format("Post/{0}", newPostId))); Assert.AreEqual(HttpStatusCode.OK, getResult.StatusCode, "GET/id API method failed"); var postLoaded = new JavaScriptSerializer().Deserialize <PostDetailsModel>(getResult.Content.ReadAsStringAsync().Result); Assert.AreEqual(newPostId, postLoaded.Id); Assert.AreEqual(newPost.Title, postLoaded.Title); Assert.AreEqual(newPost.Content, postLoaded.Content); Assert.IsNull(postLoaded.DateModified); Assert.IsTrue(postLoaded.DateCreated > DateTime.MinValue); // List posts and check that newly created post is there var listResult = await httpClient.GetAsync(ApiAction("Post")); Assert.AreEqual(HttpStatusCode.OK, listResult.StatusCode, "GET API method failed"); var listItems = new JavaScriptSerializer().Deserialize <List <PostListItemModel> >(listResult.Content.ReadAsStringAsync().Result); var postListItemLoaded = listItems.FirstOrDefault(p => p.Id == newPostId); Assert.IsNotNull(postListItemLoaded); Assert.AreEqual(newPostId, postListItemLoaded.Id); Assert.AreEqual(newPost.Title, postListItemLoaded.Title); Assert.IsTrue(postListItemLoaded.DateCreated > DateTime.MinValue); // Modifying post and saving it postLoaded.Title += "Modified"; postLoaded.Content += "Modified"; var putResult = await httpClient.PutAsJsonAsync(ApiAction("Post"), postLoaded); Assert.AreEqual(HttpStatusCode.NoContent, putResult.StatusCode, "PUT API method failed"); // Loading the post again to ensure modifications saved var getResult2 = await httpClient.GetAsync(ApiAction(string.Format("Post/{0}", newPostId))); Assert.AreEqual(HttpStatusCode.OK, getResult2.StatusCode, "GET API method failed"); var postLoaded2 = new JavaScriptSerializer().Deserialize <PostDetailsModel>(getResult2.Content.ReadAsStringAsync().Result); Assert.AreEqual(postLoaded.Title, postLoaded2.Title); Assert.AreEqual(postLoaded.Content, postLoaded2.Content); Assert.IsNotNull(postLoaded2.DateModified); Assert.IsTrue(postLoaded2.DateCreated > DateTime.MinValue); // Deleting the post we just created var deleteResult = await httpClient.DeleteAsync(ApiAction(string.Format("Post/{0}", newPostId))); Assert.AreEqual(HttpStatusCode.NoContent, deleteResult.StatusCode, "DELETE API method failed"); // List all posts again to ensure that post is deleted var listResult2 = await httpClient.GetAsync(ApiAction("Post")); Assert.AreEqual(HttpStatusCode.OK, listResult2.StatusCode, "GET API method failed"); var listItems2 = new JavaScriptSerializer().Deserialize <List <PostListItemModel> >(listResult2.Content.ReadAsStringAsync().Result); Assert.IsFalse(listItems2.Any(p => p.Id == newPostId)); } }
public ActionResult SendOrder() { var msg = new JsonMessage { Erros = false, Message = "Cảm ơn bạn đã đặt hàng, Chúng tôi sẽ liện hệ với bạn sớm nhất.!" }; try { var codeCookie = HttpContext.Request.Cookies["addtocart"]; if (codeCookie != null) { var temp = codeCookie.Value; var lst = new JavaScriptSerializer().Deserialize <List <ShopProductDetailCartItem> >(temp); var order = new Shop_Orders(); if (lst.Any()) { var listDetail = (from item in lst let product = _productDa.GetProductItem(item.ShopID ?? 0) select new Shop_Order_Details { ProductID = item.ShopID, Quantity = item.Quantity, DateCreated = DateTime.Now.TotalSeconds(), Status = 2, Price = product.PriceNew, }).ToList(); if (listDetail.Any()) { var total = listDetail.Sum(c => c.Price); order.AgencyId = 2010; order.CustomerName = Request["fullname"]; order.Mobile = Request["phone"]; order.Address = Request["address"]; order.Note = Request["ordernote"]; order.DateCreated = DateTime.Now.TotalSeconds(); order.Status = 2; order.Shop_Order_Details = listDetail; order.TotalPrice = total; order.Payments = total; order.IsDelete = false; _ordersDa.Add(order); _ordersDa.Save(); Response.Cookies["addtocart"].Expires = DateTime.Now.AddDays(-1); } else { msg = new JsonMessage { Erros = true, Message = "Giỏ hàng của bạn chưa có sản phẩm nào.!" }; } } else { msg = new JsonMessage { Erros = true, Message = "Giỏ hàng của bạn chưa có sản phẩm nào.!" }; } } else { msg = new JsonMessage { Erros = true, Message = "Giỏ hàng của bạn chưa có sản phẩm nào.!" }; } } catch (Exception) { msg = new JsonMessage { Erros = true, Message = "Có lỗi xảy ra.!" }; } return(Json(msg, JsonRequestBehavior.AllowGet)); }
public ActionResult AddListDetallesOrden(IList <string> jsonDetallesList, string code) { try { IEnumerable <DetailAssetInRequestDto> detalleList = new JavaScriptSerializer().Deserialize <IList <DetailAssetInRequestDto> >(jsonDetallesList[0]); IList <DetailAssetInRequestDto> newList = new List <DetailAssetInRequestDto>(); var asset = _inRequestService.GetAssetBarCode(code, _currentUser.CompanyName); if (asset == null) { return(Json(new { Error = -1, Message = "No se ha encontrado un artículo con este código de barra" })); } // var stock = _inRequestService.GetStockAsset(asset.Id, _currentUser.CompanyName, cellarId); bool cambio = false; if (detalleList.Any(item => item.AssetId == asset.Id && item.Delete == 0)) { cambio = true; int index = 0; foreach (var item in detalleList) { if (item.AssetId == asset.Id) { item.StockAsset = item.StockAsset + 1; //if (item.StockAsset > stock.GetStockItemsQtyBlocked()) // return Json(new { Error = -1, Message = "No hay suficientes artículos en Ubicación seleccionada. Por Favor revise las existencias." }); } item.Index = index; newList.Add(item); index++; } } if (!cambio) { DetailAssetInRequestDto detalle = new DetailAssetInRequestDto(); detalle.AssetId = asset.Id; detalle.NameAsset = asset.Name; detalle.StockAsset = 1; detalle.Price = asset.Price.ToString(); detalle.Saved = 0; detalle.Update = 1; detalle.Delete = 0; detalle.ErrorDescription = ""; detalle.ErrorCode = 0; int index = 0; foreach (var item in detalleList) { item.Index = index; newList.Add(item); index++; } detalle.Index = index; newList.Add(detalle); } return(PartialView("_tableDetails", newList)); } catch (Exception ex) { return(Json(new { Error = -1, Message = "Error al Agregar/Modificar la Solicitud" })); } }