public Response SOcc(string token, [FromBody] Aden.Model.SOMastData.SalesOrder so) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invalid token"; } else { List <Aden.Model.SOMastData.SalesOrderItem> SOcc = SalesOrderHelper.SOcc(so.companyCode, so.ownerCompanyCode, so.contract); if (SOcc != null) { response.code = "200"; response.content = SOcc; } else { response.code = "500"; response.message = "process failed"; } } return(response); }
public Response SearchCostCenterMatch(string token, [FromBody] Aden.Model.SOMastData.SalesOrderItem line) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invalid token"; } else { List <Aden.Model.SOMastData.SalesOrderItem> SearchCostCenterMatch = SalesOrderHelper.SearchCostCenterMatch(line); if (SearchCostCenterMatch != null) { response.code = "200"; response.content = SearchCostCenterMatch; } else { response.code = "500"; response.content = "process failed"; } } return(response); }
/// <summary> /// Recall a customer order by sales id. /// </summary> /// <param name="request">The request containing the sales id.</param> /// <returns>The response containing the sales order.</returns> private static RecallCustomerOrderRealtimeResponse RecallCustomerOrder(RecallCustomerOrderRealtimeRequest request) { if (request == null) { throw new ArgumentNullException("request"); } var client = new TransactionServiceClient(request.RequestContext); ReadOnlyCollection <object> transactionResponse; if (request.IsQuote) { transactionResponse = client.GetCustomerQuote(request.Id); } else { transactionResponse = client.GetCustomerOrder(request.Id, includeOnlineOrders: true); } var orderInfo = CustomerOrderInfo.FromXml(transactionResponse[0].ToString()); var order = SalesOrderHelper.GetSalesOrderFromInfo(orderInfo, request.RequestContext.GetChannelConfiguration(), request.RequestContext); // Check that the channel currency code is the same as the recalled order if (order != null && !string.IsNullOrWhiteSpace(order.CurrencyCode) && !request.RequestContext.GetChannelConfiguration().Currency.Equals(order.CurrencyCode, StringComparison.OrdinalIgnoreCase)) { throw new DataValidationException( DataValidationErrors.Microsoft_Dynamics_Commerce_Runtime_CurrencyChannelOrderMismatch, string.Format("Channel currency = {0} doesn't match sales order currency = {1}", request.RequestContext.GetChannelConfiguration().Currency, order.CurrencyCode)); } var response = new RecallCustomerOrderRealtimeResponse(order); return(response); }
public Response EditSO(string token, [FromBody] Aden.Model.SOMastData.SalesOrder so) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invild token"; } else { bool status = SalesOrderHelper.EditSO(so); if (status) { response.code = "200"; } else { response.code = "500"; response.message = "process failed"; } } return(response); }
public Response CheckContract(string token, string contract) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invild token"; } else { List <Aden.Model.SOMastData.SalesOrder> lstSO = SalesOrderHelper.CheckContract(contract); response.code = "200"; if (lstSO != null) { response.content = false; } else { response.content = true; } } return(response); }
public Response CostCenterMatch(string token, [FromBody] Aden.Model.SOMastData.SalesOrderItem line) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invalid token"; } else { int intExCount = 0; intExCount = SalesOrderHelper.CostCenterMatch(line); if (intExCount == 0) { response.code = "500"; response.message = "process failed"; } else { response.code = "200"; } } return(response); }
public Response HD(string token, [FromBody] SalesOrder so) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invalid token"; } else { List <SalesOrder> HD = SalesOrderHelper.HD(so); if (HD != null) { response.code = "200"; response.content = HD; } else { response.code = "500"; response.content = "process failed"; } } return(response); }
/// <summary> /// Creates the charge lines from a charge info collection and calculates the shipping charge amount from charge lines. /// </summary> /// <param name="chargeInfoCollection">The charge info collection.</param> /// <param name="shippingChargeCode">The shipping charge code.</param> /// <param name="beginDateTime">The begin date time of order.</param> /// <param name="shippingChargeAmount">The amount of shipping charges.</param> /// <returns>The shipping charge amount.</returns> private static List <ChargeLine> CreateChargeLines(IEnumerable <ChargeInfo> chargeInfoCollection, string shippingChargeCode, DateTimeOffset beginDateTime, out decimal shippingChargeAmount) { List <ChargeLine> chargeLines = new List <ChargeLine>(); shippingChargeAmount = decimal.Zero; foreach (ChargeInfo charge in chargeInfoCollection) { ChargeLine chargeLine = SalesOrderHelper.CreateChargeLine(charge); if (!chargeLine.BeginDateTime.IsValidAxDateTime()) { chargeLine.BeginDateTime = beginDateTime.UtcDateTime; } if (!chargeLine.EndDateTime.IsValidAxDateTime()) { chargeLine.EndDateTime = DateTimeOffsetExtensions.AxMaxDateValue.UtcDateTime; } chargeLines.Add(chargeLine); if (chargeLine.ChargeCode.Equals(shippingChargeCode, StringComparison.OrdinalIgnoreCase)) { shippingChargeAmount += chargeLine.CalculatedAmount; } } return(chargeLines); }
public Response CreateSO(string token, [FromBody] Aden.Model.SOMastData.SalesOrder so) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invild token"; } else { string headGuid = SalesOrderHelper.CreateSO(so); if (!string.IsNullOrWhiteSpace(headGuid)) { response.code = "200"; response.content = headGuid; } else { response.code = "500"; response.message = "process failed"; } } return(response); }
public Response MenuAction(string token, string userGuid, string Company, string action) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invalid token"; } else { MenuAction menuAction = SalesOrderHelper.MenuAction(userGuid, Company, action); if (menuAction != null) { response.code = "200"; response.content = menuAction; } else { response.code = "500"; response.message = "process failed"; } } return(response); }
public Response SearchSO(string token, string db, string sDate, string eDate) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invild token"; } else { List <Aden.Model.SOMastData.SalesOrder> solist = SalesOrderHelper.SearchSO(db, sDate, eDate); if (solist != null) { response.code = "200"; response.content = solist; } else { response.code = "500"; response.message = "process failed"; } } return(response); }
public Response SODetail(string token, string company) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invalid token"; } else { List <Aden.Model.SOMastData.SalesOrderItem> SODetail = SalesOrderHelper.SODetail(company); if (SODetail != null) { response.code = "200"; response.content = SODetail; } else { response.code = "500"; response.message = "process failed"; } } return(response); }
public Response QuerySO(string token) { Response response = new Response(); if (string.IsNullOrEmpty(token) || !token.Equals(_token)) { response.code = "404"; response.message = "Invild token"; } else { List <Aden.Model.SOMastData.SalesOrder> so = SalesOrderHelper.QuerySO(); response.code = "200"; if (so != null) { response.code = "200"; response.content = so; } else { response.code = "500"; } } return(response); }
internal bool ProcessSalesOrders(List <SalesOrderObject> salesOrders, int vendorID) { using (var database = new Database(Environments.Current.Connection, "System.Data.SqlClient")) { database.BeginTransaction(IsolationLevel.ReadCommitted); var counter = 0; try { foreach (var order in salesOrders) { //Create Order var orderID = SalesOrderHelper.CreateSalesOrderAndReturnOrderID(order, database); //Create all orderlines foreach (var orderLine in order.SalesOrderLines) { //Don't forget to set the correct OrderID orderLine.SalesOrderID = orderID; SalesOrderHelper.CreateSalesOrderLineAndReturnOrderLineID(orderLine, vendorID, order.IsSalesOrder, order.ReceivedDate, database); } counter++; if (counter % 25 == 0) { log.Debug(string.Format("Processed {0} orders to database", counter)); } } } catch (Exception ex) { database.AbortTransaction(); log.AuditError("Error in ProcessSalesOrders", ex); return(false); } //Success database.CompleteTransaction(); log.Debug(string.Format("Processed {0} orders to database", counter)); return(true); } }
public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SalesOrder salesOrder = _salesContext.SalesOrders.Find(id); if (salesOrder == null) { return(HttpNotFound()); } SalesOrderViewModel viewModel = SalesOrderHelper.CreateSalesOrderViewModelFromSalesOrder(salesOrder); viewModel.MessageToClient = "I originated from the viewmodel, rather that the model."; return(View(viewModel)); }
public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SalesOrder salesOrder = _salesContext.SalesOrders.Find(id); if (salesOrder == null) { return(HttpNotFound()); } SalesOrderViewModel viewModel = SalesOrderHelper.CreateSalesOrderViewModelFromSalesOrder(salesOrder); viewModel.MessageToClient = string.Format("You are about to delete this sales order"); //Because in the helper method object state is set to unchanged, it needs to be set to deleted here viewModel.ObjectState = ObjectState.Deleted; return(View(viewModel)); }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SalesOrder salesOrder = _salesContext.SalesOrders.Find(id); if (salesOrder == null) { return(HttpNotFound()); } SalesOrderViewModel viewModel = SalesOrderHelper.CreateSalesOrderViewModelFromSalesOrder(salesOrder); viewModel.MessageToClient = string.Format("The original value of the Customer Name is {0}", salesOrder.CustomerName); return(View(viewModel)); }
private void btnSearch_Click(object sender, EventArgs e) { _MySessionManager = SessionManager.NewQBSession(); if (txtSalesOrderNumberSearch.Text.Trim() == "") { MessageBox.Show("Please enter a Sales Order number to search"); return; } try { int salesOrder = Convert.ToInt32(txtSalesOrderNumberSearch.Text.Trim()); } catch (InvalidCastException) { MessageBox.Show("Please enter numbers only in the Sales Order number textbox"); return; } try { SalesOrderHelper salesOrderHelper = new SalesOrderHelper(_MySessionManager); _salesOrder = salesOrderHelper.Populate(txtSalesOrderNumberSearch.Text); txtSalesOrderNumber.Text = _salesOrder.Number; txtDate.Text = _salesOrder.Date.ToShortDateString(); txtShipDate.Text = _salesOrder.ShipDate.ToString(); txtTotalPrice.Text = _salesOrder.Total; txtTotalQuantity.Text = _salesOrder.TotalQty.ToString(); txtCustomerName.Text = _salesOrder.CustomerFullName; txtBillingAddress.Text = _salesOrder.BillingAddress; txtShippingAddress.Text = _salesOrder.ShippingAddress; dgSalesOrder.Columns.Clear(); dt = new DataTable(); dt.Columns.Add("Item Code"); dt.Columns.Add("UPC"); dt.Columns.Add("Description"); dt.Columns.Add("Quantity"); dt.Columns.Add("Price"); dt.Columns.Add("Amount"); foreach (InventoryItem item in _salesOrder.InventoryItems) { DataRow dr = dt.NewRow(); dr["Item Code"] = item.ItemCode; dr["Description"] = item.Description; dr["Quantity"] = item.Quantity; dr["Price"] = item.Price; dr["Amount"] = item.Amount; dr["UPC"] = item.MPN; dt.Rows.Add(dr); } dgSalesOrder.DataSource = dt; dgSalesOrder.Columns[0].Width = 100; dgSalesOrder.Columns[1].Width = 100; dgSalesOrder.Columns[2].Width = 300; dgSalesOrder.Columns[3].Width = 70; dgSalesOrder.Columns[4].Width = 70; dgSalesOrder.Columns[5].Width = 70; Pictures p = new Pictures(); p.Populate(ref dgSalesOrder, _salesOrder.InventoryItems, Settings.Default.ImagesLocation); } catch (Exception ex) { disconnectQB(); MessageBox.Show(ex.Message, "Error in Program", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public static SalesOrder GetSalesOrderFromInfo(CustomerOrderInfo orderInfo, ChannelConfiguration channelConfiguration, RequestContext context) { // Stores the local copy. There is high probability of having the same shipping/delivery address on all the lines. Dictionary <long, Address> shippingAddressDictionary = new Dictionary <long, Address>(); decimal shippingChargeAmount; ColumnSet columnSet = new ColumnSet(); var salesOrder = new SalesOrder { SalesId = orderInfo.Id, TransactionType = SalesTransactionType.CustomerOrder, CustomerOrderMode = CustomerOrderMode.OrderRecalled, CartType = CartType.CustomerOrder, CustomerOrderType = orderInfo.OrderType, StoreId = orderInfo.StoreId, IsTaxIncludedInPrice = Convert.ToBoolean(orderInfo.IsTaxIncludedInPrice) }; switch (orderInfo.OrderType) { case CustomerOrderType.Quote: salesOrder.Status = Utilities.GetSalesStatus((SalesQuotationStatus)orderInfo.Status); break; case CustomerOrderType.SalesOrder: salesOrder.Status = Utilities.GetSalesStatus((SalesOrderStatus)orderInfo.Status, (DocumentStatus)orderInfo.DocumentStatus); break; default: salesOrder.Status = SalesStatus.Unknown; break; } DateTimeOffset currentChannelDate = context.GetNowInChannelTimeZone(); salesOrder.RequestedDeliveryDate = Utilities.ParseDateStringAsDateTimeOffset(orderInfo.RequestedDeliveryDateString, currentChannelDate.Date, currentChannelDate.Offset); salesOrder.QuotationExpiryDate = Utilities.ParseDateStringAsDateTimeOffset(orderInfo.ExpiryDateString, currentChannelDate.Date, currentChannelDate.Offset); // CreationDate is stored in UTC. It needs to be converted to local time zone where order is accessed. salesOrder.BeginDateTime = Utilities.ParseDateString(orderInfo.CreationDateString, currentChannelDate.ToUniversalTime().DateTime, DateTimeStyles.AssumeUniversal); salesOrder.Comment = orderInfo.Comment; // Header delivery salesOrder.InventoryLocationId = orderInfo.WarehouseId; salesOrder.DeliveryMode = orderInfo.DeliveryMode; foreach (var discountCode in orderInfo.DiscountCodes) { salesOrder.DiscountCodes.Add(discountCode); } // Customer info salesOrder.CustomerId = orderInfo.CustomerAccount; long addressRecordIdLong = 0; if (long.TryParse(orderInfo.AddressRecordId, out addressRecordIdLong)) { var dataServiceRequest = new GetAddressDataRequest(addressRecordIdLong, columnSet); SingleEntityDataServiceResponse <Address> dataServiceResponse = context.Execute <SingleEntityDataServiceResponse <Address> >(dataServiceRequest); if (dataServiceResponse.Entity == null) { Utilities.DownloadCustomerData(context, salesOrder.CustomerId); dataServiceResponse = context.Execute <SingleEntityDataServiceResponse <Address> >(dataServiceRequest); } if (dataServiceResponse.Entity != null) { salesOrder.ShippingAddress = dataServiceResponse.Entity; shippingAddressDictionary.Add(salesOrder.ShippingAddress.RecordId, salesOrder.ShippingAddress); } } if (!string.IsNullOrEmpty(orderInfo.SalespersonStaffId)) { // Sets the sales person id and name according to AX values // This is done because we do not know whether the sales person information is available on this store salesOrder.StaffId = orderInfo.SalespersonStaffId; } salesOrder.ChannelReferenceId = orderInfo.ChannelReferenceId; salesOrder.LoyaltyCardId = orderInfo.LoyaltyCardId; salesOrder.ReceiptEmail = orderInfo.Email; string shippingChargeCode = channelConfiguration.ShippingChargeCode; // Items int lineId = 0; foreach (ItemInfo item in orderInfo.Items) { lineId++; var lineItem = new SalesLine { LineId = lineId.ToString(CultureInfo.InvariantCulture), Found = true, RecordId = item.RecId, ItemId = item.ItemId, Comment = item.Comment, Quantity = item.Quantity, ReturnQuantity = item.Quantity, SalesOrderUnitOfMeasure = item.Unit, UnitOfMeasureSymbol = item.Unit, Price = item.Price, NetAmount = item.NetAmount, QuantityOrdered = item.Quantity, QuantityInvoiced = item.QuantityPicked, DeliveryMode = item.DeliveryMode, RequestedDeliveryDate = Utilities.ParseDateStringAsDateTimeOffset(item.RequestedDeliveryDateString, currentChannelDate.Date, currentChannelDate.Offset), FulfillmentStoreId = item.FulfillmentStoreId, InventoryLocationId = item.WarehouseId, SerialNumber = item.SerialId, BatchId = item.BatchId, Status = TransactionStatus.Normal, SalesStatus = Utilities.GetSalesStatus((SalesOrderStatus)item.Status) }; // Copy charges to line and calculates total shipping charge amount lineItem.ChargeLines.AddRange(SalesOrderHelper.CreateChargeLines(item.Charges, shippingChargeCode, salesOrder.BeginDateTime, out shippingChargeAmount)); lineItem.DeliveryModeChargeAmount = shippingChargeAmount; // Line level discount amounts lineItem.LineDiscount = item.LineDscAmount; lineItem.PeriodicDiscount = item.PeriodicDiscount; lineItem.PeriodicPercentageDiscount = item.PeriodicPercentageDiscount; lineItem.LineManualDiscountAmount = item.LineManualDiscountAmount; lineItem.LineManualDiscountPercentage = item.LineManualDiscountPercentage; lineItem.TotalDiscount = item.TotalDiscount; lineItem.TotalPercentageDiscount = item.TotalPctDiscount; // Copy discounts to line lineItem.DiscountLines.AddRange(SalesOrderHelper.CreateDiscountLines(item.Discounts)); long itemAddressRecordIdLong; if (long.TryParse(item.AddressRecordId, out itemAddressRecordIdLong)) { Address lineLevelshippingAddress = new Address(); if (!shippingAddressDictionary.TryGetValue(itemAddressRecordIdLong, out lineLevelshippingAddress)) { var dataServiceRequest = new GetAddressDataRequest(itemAddressRecordIdLong, columnSet); SingleEntityDataServiceResponse <Address> dataServiceResponse = context.Execute <SingleEntityDataServiceResponse <Address> >(dataServiceRequest); // If address not found download and get. if (dataServiceResponse.Entity == null) { Utilities.DownloadCustomerData(context, salesOrder.CustomerId); dataServiceResponse = context.Execute <SingleEntityDataServiceResponse <Address> >(dataServiceRequest); } if (dataServiceResponse.Entity != null) { lineItem.ShippingAddress = dataServiceResponse.Entity; shippingAddressDictionary.Add(lineItem.ShippingAddress.RecordId, lineItem.ShippingAddress); } } else { lineItem.ShippingAddress = lineLevelshippingAddress; } } Utilities.SetUpVariantAndProduct(context, item.InventDimensionId, lineItem.ItemId, lineItem); lineItem.DiscountAmount = item.Discount; // Set tax info after defaults, as it may have been overridden. lineItem.SalesTaxGroupId = item.SalesTaxGroup ?? string.Empty; lineItem.ItemTaxGroupId = item.ItemTaxGroup ?? string.Empty; // Add it to the transaction salesOrder.SalesLines.Add(lineItem); } // Charges for the header salesOrder.ChargeLines.AddRange(SalesOrderHelper.CreateChargeLines(orderInfo.Charges, shippingChargeCode, salesOrder.BeginDateTime, out shippingChargeAmount)); salesOrder.DeliveryModeChargeAmount = shippingChargeAmount; // Payments // - total up amounts // - add history entries decimal nonPrepayments = decimal.Zero; decimal prepaymentAmountPaid = decimal.Zero; int tenderLineId = 0; foreach (PaymentInfo payment in orderInfo.Payments) { if (salesOrder.TenderLines == null) { salesOrder.TenderLines = new Collection <TenderLine>(); } decimal amount = 0M; if (string.IsNullOrWhiteSpace(payment.Currency) || payment.Currency.Equals(channelConfiguration.Currency, StringComparison.OrdinalIgnoreCase)) { amount = payment.Amount; } else { GetCurrencyValueServiceRequest currencyValueRequest = new GetCurrencyValueServiceRequest(payment.Currency, channelConfiguration.Currency, payment.Amount); GetCurrencyValueServiceResponse currencyValueResponse = context.Execute <GetCurrencyValueServiceResponse>(currencyValueRequest); amount = currencyValueResponse.RoundedConvertedAmount; } if (payment.Prepayment) { // Sum prepayments to track total deposits paid prepaymentAmountPaid += amount; } else { // Sum non-prepayments as base for calculating deposits applied to pickups nonPrepayments += amount; } tenderLineId++; var tenderLine = new TenderLine { TenderLineId = tenderLineId.ToString(CultureInfo.InvariantCulture), Amount = payment.Amount, Currency = payment.Currency, CardTypeId = string.Empty, Status = TenderLineStatus.Historical, IsVoidable = false, TenderDate = Utilities.ParseDateString( payment.DateString, currentChannelDate.Date, DateTimeStyles.None) // On channel timezone }; salesOrder.TenderLines.Add(tenderLine); } if (orderInfo.Affiliations != null && orderInfo.Affiliations.Any()) { salesOrder.AffiliationLoyaltyTierLines.Clear(); salesOrder.AffiliationLoyaltyTierLines.AddRange(orderInfo.Affiliations.Select(line => new SalesAffiliationLoyaltyTier { AffiliationId = line.AffiliationRecordId, LoyaltyTierId = line.LoyaltyTierRecordId, AffiliationType = line.AffiliationType })); } // Prepayment/Deposit override info if (orderInfo.PrepaymentAmountOverridden) { salesOrder.OverriddenDepositAmount = prepaymentAmountPaid; } salesOrder.PrepaymentAmountPaid = prepaymentAmountPaid; // Portion of the prepayment that has been applied to invoices // (total amount invoiced less payments, difference is the deposit applied) salesOrder.PrepaymentAmountInvoiced = orderInfo.PreviouslyInvoicedAmount - nonPrepayments; // if the prepayment invoiced is greater than the total paid as deposit, there is no credit left salesOrder.AvailableDepositAmount = Math.Max(decimal.Zero, salesOrder.PrepaymentAmountPaid - salesOrder.PrepaymentAmountInvoiced); salesOrder.HasLoyaltyPayment = orderInfo.HasLoyaltyPayment; salesOrder.CurrencyCode = orderInfo.CurrencyCode; return(salesOrder); }
public JsonResult Save(SalesOrderViewModel salesOrderViewModel) { SalesOrder salesOrder = SalesOrderHelper.CreateSalesOrderFromSalesOrderViewModel(salesOrderViewModel); salesOrder.ObjectState = salesOrderViewModel.ObjectState; //instead of hard coding salesOrder as an add, attach it instead _salesContext.SalesOrders.Attach(salesOrder); //Check to see if objectstate for the salesorder is delete if (salesOrder.ObjectState == ObjectState.Deleted) { //Loop through all the salesorderitems in the view model and set their object state to deleted foreach (SalesOrderItemViewModel salesOrderItemViewModel in salesOrderViewModel.SalesOrderItems) { SalesOrderItem salesOrderItem = _salesContext.SalesOrderItems.Find(salesOrderItemViewModel.SalesOrderItemId); if (salesOrderItem != null) { salesOrderItem.ObjectState = ObjectState.Deleted; } } } else { //This will loop through the SalesOrderItems marked for deleting on the client, //find the corresponding record in the context and set it to be deleted in EF foreach (int salesOrderItemId in salesOrderViewModel.SalesOrderItemsToDelete) { SalesOrderItem salesOrderItem = _salesContext.SalesOrderItems.Find(salesOrderItemId); if (salesOrderItem != null) { salesOrderItem.ObjectState = ObjectState.Deleted; } } } //Then you want to tell the change tracker to set the state that was returned from the helper method //created in the SolutionName.Model //_salesContext.ChangeTracker.Entries<IObjectWithState>().Single().State = // Helpers.ConvertState(salesOrder.ObjectState); _salesContext.ApplyStateChanges(); _salesContext.SaveChanges(); //Since when an item is deleted we don't want to return a aview the //Delete will return a anonymous Json object that will return a single property called new laoction //whose value is the controller action for displaying the list of sales orders. if (salesOrder.ObjectState == ObjectState.Deleted) { //This will be returned to the view we don't want to stay on we we need a way for the view //to redirect to the sales order list which is /Sales/Index. See line 34 in salesorderviewmodel.js return(Json(new { newLocation = "/Sales/Index/" })); } string messageToClient = SalesOrderHelper.GetMessageToClient(salesOrderViewModel.ObjectState, salesOrderViewModel.CustomerName); //If a record is inserted the context is synced with the ID but that is never communicated back to the client //so the SalesOrderId needs to be set with the value returned from the DB //salesOrderViewModel.SalesOrderId = salesOrder.SalesOrderId; salesOrderViewModel = ViewModels.SalesOrderHelper.CreateSalesOrderViewModelFromSalesOrder(salesOrder); salesOrderViewModel.MessageToClient = messageToClient; //to make the Json object as flexible enough for all our needs we will send back an annoymous object //that contains whatever we need to send to the client and then let the client insepct the contents to //determine what to do with it return(Json(new { salesOrderViewModel })); }